License YOLO
Back to Ultralytics Glossary

Task Vectors

A task vector is the difference between a model's fine-tuned and pretrained weights, a direction in weight space that can be scaled, added, or negated.

A task vector is the element-wise difference between a model's weights after fine-tuning on a task and its pretrained weights: τ = θ_fine-tuned − θ_pretrained. It records everything fine-tuning changed as one direction in weight space, so the skill can be stored, scaled, combined with other skills, or removed by plain arithmetic on model weights instead of more training. Adding the full task vector back to the pretrained weights reproduces the fine-tuned model, adding half of it moves halfway, and subtracting it moves away from the task. Gabriel Ilharco and colleagues at the University of Washington, Microsoft Research, and the Allen Institute for AI introduced the term in Editing Models with Task Arithmetic, published at ICLR 2023, where they showed that negating task vectors makes a model forget a task and adding them builds a multi-task model.

Structure of a Task Vector#

A task vector has one entry for every parameter of the neural network, so it is as large as the model itself, about 124 million numbers for GPT-2. It is only meaningful relative to the pretrained weights it was computed from, which means it can be applied to models with the same architecture that start from the same pretrained checkpoint. Applying it uses a scaling coefficient λ, giving θ_new = θ_pretrained + λτ, and Ilharco et al. chose λ on held-out validation data.

Which entries are nonzero depends on what fine-tuning was allowed to change. In Ultralytics YOLO26 training, the freeze argument freezes the first N layers, keeping their weights and batch-normalization statistics fixed, so the task vector between the starting yolo26n.pt checkpoint and the resulting best.pt is exactly zero in those layers and the new skill lives entirely in the rest of the network.

Task vectors have two properties that make arithmetic on them work. First, vectors from different tasks are close to orthogonal: across eight image classification tasks fine-tuned from CLIP, their cosine similarities were near zero, highest between related tasks such as the digit datasets MNIST and SVHN, so adding one vector disturbs little of what another encodes. Second, they are highly redundant. DARE, by Le Yu and colleagues, randomly drops 90% or even 99% of the entries in a fine-tuning delta and multiplies the rest by 1/(1 − p), where p is the drop rate, with little loss of the fine-tuned ability.

This PyTorch example fine-tunes GPT-2 from Hugging Face Transformers on three short Python functions, extracts the task vector, and applies it to the pretrained model at different scales and with 90% of its entries randomly dropped:

import copy

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

torch.manual_seed(0)
tokenizer = AutoTokenizer.from_pretrained("gpt2")
base = AutoModelForCausalLM.from_pretrained("gpt2")
code = [
    "def add(a, b):\n    return a + b\n",
    "def square(x):\n    return x * x\n",
    "def is_even(n):\n    return n % 2 == 0\n",
]


def loss(model, text="def subtract(a, b):\n    return a - b\n"):
    """Next-token cross-entropy of the model on the text, by default a function it was not tuned on."""
    ids = tokenizer(text, return_tensors="pt").input_ids
    return model(ids, labels=ids).loss


# Fine-tune a copy of GPT-2 on three short Python functions
tuned = copy.deepcopy(base)
optimizer = torch.optim.Adam(tuned.parameters(), lr=5e-5)
for _ in range(20):
    optimizer.zero_grad()
    sum(loss(tuned, text) for text in code).backward()
    optimizer.step()

# Task vector: fine-tuned minus pretrained weights, one tensor per parameter
pretrained = dict(base.named_parameters())
task_vector = {name: p.detach() - pretrained[name].detach() for name, p in tuned.named_parameters()}

for label, edit in [
    ("Pretrained", lambda tau: 0 * tau),
    ("+ task vector", lambda tau: tau),
    ("+ 0.5 x task vector", lambda tau: 0.5 * tau),
    ("+ random 10% of entries x 10", lambda tau: tau * (torch.rand_like(tau) < 0.1) * 10),  # DARE-style
]:
    model = copy.deepcopy(base)
    with torch.no_grad():
        for name, p in model.named_parameters():
            p += edit(task_vector[name])
        print(f"{label}: loss on unseen code {loss(model).item():.2f}")

The pretrained model's loss on an unseen subtract function is 4.04. Adding the full task vector lowers it to 1.22, and adding half of it gives 1.13, so a scaled-down vector keeps the skill here and even generalizes slightly better. Keeping a random 10% of the entries and multiplying them by 10 also gives 1.22, the same as the full vector.

Where Task Vectors Are Used#

Task arithmetic is the main use: adding the vectors of several tasks gives one multi-task model, and Ilharco et al. reduced the share of toxic generations from GPT-2 Large from 4.8% to 0.8% by subtracting a vector fine-tuned on toxic comments, a form of machine unlearning. Model merging methods such as TIES-Merging trim small entries from each task vector and resolve sign conflicts between vectors before adding them, and open-source tools such as mergekit apply these recipes to large language models (LLMs).

A fine-tune can also be shared as its task vector when the base weights cannot be redistributed. LMSYS released the first Vicuna weights as deltas to be added to Meta's LLaMA weights for this reason.

  • Steering vectors: Directions in activation space, added to a layer's outputs on every forward pass. Task vectors change the weights once, and the edited model then runs like any other.
  • LoRA: Trains a low-rank update B × A for selected weight matrices. That update is a task vector constrained to low rank, and merging a LoRA adapter into a model adds it to the weights exactly as a task vector is added.
  • Transfer learning: Produces the fine-tuned model in the first place. The task vector is the record of what transfer learning changed, measured against the starting checkpoint.
  • Model soups: Average several fine-tunes of the same task. In task-vector terms, a uniform soup of two fine-tunes equals the pretrained weights plus the average of their two task vectors.

Explore solutions

Computer vision in sports

Computer vision in sports

Discover how Ultralytics YOLO powers sports vision with player and ball tracking, performance analytics, coaching insights, and athlete rehabilitation.
Learn more
Computer vision for aerial imagery

Computer vision for aerial imagery

Turn drone and aerial imagery into real-time insights for agriculture, aquaculture, conservation, and geospatial analysis with Ultralytics YOLO.
Learn more
Computer vision in aerospace

Computer vision in aerospace

Apply computer vision in aerospace with Ultralytics YOLO for aircraft inspection, runway FOD detection, airport ground operations, and composite defect detection.
Learn more
Computer vision in security

Computer vision in security

Protect every site with Ultralytics YOLO models. Vision AI powers perimeter monitoring, threat detection, license-plate recognition, and workplace safety.
Learn more
Computer vision in robotics

Computer vision in robotics

Power smarter machines with Ultralytics YOLO models. Vision AI in robotics drives autonomous navigation, perception, object tracking, and real-time control.
Learn more
Computer vision in logistics

Computer vision in logistics

Streamline logistics with Ultralytics YOLO models. Vision AI enables package inspection, sorting, vehicle tracking, and real-time warehouse safety monitoring.
Learn more
Computer vision in retail

Computer vision in retail

Reimagine retail with Ultralytics YOLO models. Vision AI powers inventory tracking, shelf monitoring, queue management, and smarter customer insights.
Learn more
Computer vision in healthcare

Computer vision in healthcare

Build healthcare solutions with Ultralytics YOLO models. Vision AI in healthcare powers faster medical imaging, smarter diagnostics, and patient monitoring.
Learn more
Computer vision in manufacturing

Computer vision in manufacturing

Optimize manufacturing with Ultralytics YOLO models. Vision AI drives quality control, defect detection, PPE compliance, and assembly line automation.
Learn more
Computer vision in automotive

Computer vision in automotive

Apply computer vision in automotive with Ultralytics YOLO models. Vision AI elevates road safety, driver assistance, and vehicle automation for smarter roads.
Learn more
Computer vision in agriculture

Computer vision in agriculture

Bring vision AI to smart agriculture with Ultralytics YOLO models. Power crop monitoring, livestock tracking, and precision farming for higher, smarter yields.
Learn more

Let's build the future of AI together!

Begin your journey with the future of machine learning