Red teaming Hugging Face models with PyRIT

Learn how PyRIT's HuggingFaceChatTarget runs attacks against locally loaded Hugging Face models, and when a hosted endpoint is the better objective target for long scenarios.

On this page

How PyRIT red teams Hugging Face models you load yourself

A team that wants to test a Hugging Face model before release or rollout has two practical routes in PyRIT. PyRIT includes a HuggingFaceChatTarget for Hugging Face models, so the choice is between loading the model locally through that target and pointing PyRIT at a hosted endpoint that serves the model. Local loading keeps the model weights and every prompt inside hardware you control, which suits short, controlled test runs. A hosted endpoint is usually the better objective target when a scenario is long, needs many turns, or must run on the same serving stack the product uses in production.

The integration covers sending prompts to a model that PyRIT loads, recording the conversation in PyRIT memory, and passing responses to scorers and multi-turn attacks such as Crescendo. It does not cover choosing a model for you, judging whether a response is harmful, or testing the application around the model, such as its system prompt, retrieval layer, tools or access controls. Those parts need their own targets, scorers and review steps. Confirm the exact constructor arguments, model identifiers and hardware requirements for your PyRIT version in the HuggingFace Chat Target documentation before you write a test plan, since local loading depends on your accelerators and model size.

Before you start, decide which model you will test and record its exact revision, license terms and gating requirements, because the same model name can change over time. Check that the host has enough memory and accelerator capacity for the model and for the attack model you plan to run alongside it. Keep the Hugging Face access token in the PyRIT environment file rather than in scripts, and confirm who may read the memory database that stores the test conversations, since those records may contain harmful outputs.

What you need before the first Hugging Face attack run

Most delays on a first Hugging Face run come from the environment, not the attack. The cards below cover the Python runtime, the install, the local hardware, model access and the two configuration files PyRIT reads, so the first run can focus on the objective and the scoring.

Python runtime version

The PyPI package supports Python 3.10 up to but not including 3.15, and the PyRIT documentation recommends Python 3.13. Pick the interpreter before creating the virtual environment, because a mismatch often surfaces later as a dependency install failure. Confirm the version your team's build images and developer machines already run, and align them so every engineer reproduces the same results.

PyPI package page

Installing PyRIT from PyPI

PyRIT installs with pip from the pyrit package on PyPI. Install it into a dedicated virtual environment, pin the version your team tests against, and record that version with each run so results can be reproduced. Upgrades can change target and scorer behavior, so treat the version as part of the evidence trail.

PyRIT documentation

Hardware for local models

Local Hugging Face models need memory and accelerator capacity that depends on each model's size, precision and context length. Confirm the requirements for every model on your list before the run, including whether the model runs on CPU, a single GPU or several. Running out of memory mid-attack wastes the conversation history, so test one model end to end first.

Model license and access terms

Each Hugging Face model carries its own license and may require accepting terms or an access token before download. Check whether the license permits your use case, including security testing and internal evaluation, and record who accepted the terms. Gated models can fail to load on machines where the account is not authorized, so confirm access for every engineer who will run the tests.

Credentials in the .env file

PyRIT reads credentials from ~/.pyrit/.env. Keep Hugging Face tokens and any keys for scorer or adversarial models there, not in scripts or shell history. Restrict the file to the account that runs the tests, and confirm that tokens are scoped to the minimum access needed for the models in scope.

Settings in the .pyrit_conf file

PyRIT reads its settings from ~/.pyrit/.pyrit_conf. Set memory and default options here so every run on the team's machines behaves the same way. Store the file under version control in your team's configuration repository where possible, and review changes to it the same way you review code.

How to configure the HuggingFace chat target step by step

This sequence takes a team from an empty environment to a working PyRIT run against a Hugging Face model loaded locally, with each step closed by a check that proves it worked. The output is a verified single-turn result and a verified multi-turn result that the team can rerun and review.

  1. Install PyRIT in a supported Python environment

    The engineer who runs the tests creates an isolated virtual environment and installs PyRIT from PyPI with pip. The PyPI package supports Python 3.10 up to but not including 3.15, and the documentation recommends Python 3.13, so confirm the interpreter version before installing. Done means pip show pyrit reports an installed version and python -c "import pyrit" runs without error inside that environment.

  2. Choose the model and confirm it loads

    Select a Hugging Face model that your organization has approved for testing, and record its exact model ID, license and revision. Load it once with the Hugging Face libraries in the same environment, outside PyRIT, so that hardware, memory and download problems surface before any PyRIT code runs. Confirm that the model's chat template matches the format you expect, because the target depends on it. Done means the model loads and produces a reply to a short test message.

  3. Configure the HuggingFaceChatTarget

    Create the target using the HuggingFaceChatTarget class, following the parameters described in the PyRIT documentation for the version you installed. Set the model ID and the device or runtime options that match your hardware, and keep the model cache in a location your security team has approved. Store any access tokens in ~/.pyrit/.env rather than in notebooks or scripts, and set non-secret options in ~/.pyrit/.pyrit_conf. Done means the target object is created without error and reports the model ID you chose. The current parameter names are in the PyRIT HuggingFace chat target documentation.

  4. Set memory to SQLite or Azure SQL

    Choose where PyRIT records conversations and scores. SQLite is the simpler option for a local run, and Azure SQL suits teams that need shared storage. Initialize the memory before the first attack so every prompt, response and score is saved. Keep the database file in a restricted directory, because it will contain harmful prompts and outputs. Done means a test prompt sent through the target appears in the memory store when you query it.

  5. Add an objective and a scorer

    Write or select one objective that describes the behavior you are testing for, such as a request the model's policy should refuse. Pair it with a scorer that decides whether the response met the objective. PyRIT scorers can use an LLM, Azure AI Content Safety or custom logic, and for a first run a simple, inspectable scorer is easier to check by hand. Done means the scorer returns a result for a sample response you wrote yourself, and you can explain why it returned that result.

  6. Run a single-turn check

    Run one prompt through the target with the scorer attached, using a single-turn attack. The reviewer reads the stored prompt, the model's reply and the score side by side in memory. Confirm that the response was recorded in full, that the score matches what a human reading the reply would conclude, and that rerunning the same prompt produces a record with the same structure. Done means one complete, scored conversation exists in memory and a second reviewer reaches the same reading.

  7. Run a multi-turn check

    Move to a multi-turn attack that keeps conversation history between turns, which the local target supports through the same conversation memory. Limit the first run to a small number of turns so that you can inspect each reply. Check that earlier turns are included in later prompts and that the scorer evaluates the final reply against the objective. Done means the stored conversation shows every turn in order, the history carries through, and the final score is recorded with its turn number.

How the attack loop reaches a local model or a hosted endpoint

The loop starts in the PyRIT attack, which sends each objective through the target and records every turn. A local HuggingFaceChatTarget loads the model inside your environment, while a hosted endpoint is the alternative objective target for long scenarios. The adversarial and scoring models feed the attack loop, and SQLite or Azure SQL memory keeps the record of each turn. Check which target path your scenario uses, and confirm that the scorer and adversarial models stay where your data rules allow.

Attack loop, objective target paths, supporting models and the memory store.

When local loading or a hosted endpoint is the better target

Local loading suits short, single-turn checks where you send a prompt, read one response and score it. A small set of objectives can be run in a single session with little setup beyond the model files and a machine that can hold the model in memory. The cost of a single-turn run is mostly hardware time, and the results stay on the machine that ran them.

  • Fast feedback loops: Quick probes of a new model checkpoint or a candidate system prompt do not need a shared service to be provisioned first.
  • Controlled model version: You pin the exact weights you downloaded, which helps when you need to rerun the same test against the same artifact.
  • Low coordination cost: One engineer can run the scan without asking another team for endpoint access or keys.
  • Limited concurrency: Throughput depends on the hardware in front of you, so large objective sets may take much longer than they would against a provisioned service.
  • Scoring still needs a model: An LLM-based scorer or adversarial model must also run somewhere, so plan its hardware alongside the target.

Before you rely on local runs for evidence, confirm the supported model classes, device settings and memory requirements in the PyRIT documentation.

How PyRIT fields map to Hugging Face model settings

This table maps each part of a PyRIT Hugging Face run to the setting it controls and the record it leaves behind. Read it before you start a long scenario, because the model identifier, chat template and generation settings decide what the model actually receives. Items marked as to verify should be checked against the HuggingFaceChatTarget documentation and your installed PyRIT version before you rely on them.

Field or recordWhat it controlsWhat to verify before a run
Model identifierSelects the Hugging Face model the local target loads, such as the repository name you pass to the targetConfirm the exact parameter name and that the model is downloaded to a path your team can reproduce
Chat templateFormats system, user and assistant turns into the prompt string the model was trained to readConfirm whether the template comes from the model's tokenizer or from PyRIT, since a mismatch changes refusal behavior
Generation settingsControl sampling such as maximum new tokens, temperature and top-p, which change output variability across attemptsConfirm which generation keys the target accepts and record their values per scenario for repeatability
Device and precisionDecide whether the model runs on CPU or GPU and at what precision, which affects speed and memory useConfirm supported options in your environment, since the setting can change outputs slightly
Conversation historyHolds prior user and assistant turns that multi-turn attacks such as Crescendo send back on each stepConfirm how the target handles history length, since long context may be truncated by the model's window
Memory recordsStore each prompt, response and score in SQLite or Azure SQL so each turn can be traced to its runConfirm that the conversation ID and model identifier are saved with every turn for audit review
Credentials fileHolds any token needed to download gated models, read from ~/.pyrit/.envConfirm the variable name in the documentation and keep the token out of scenario logs

Securing local model credentials, data and test records

Running PyRIT against local Hugging Face models creates three kinds of sensitive material: access tokens, adversarial prompts with model outputs, and the test host itself. The cards below cover how to contain each one and how to report a PyRIT defect if you find one.

Keep Hugging Face tokens out of code

Store the Hugging Face access token in ~/.pyrit/.env rather than in notebooks, scripts or shell history, and keep the file readable only by the account that runs PyRIT. Check that test code, logs and exported conversations never echo the token. Confirm with your security team how tokens are issued, scoped and rotated for gated model downloads, since a token leaked from a red teaming host can expose private repositories as well as model access.

HuggingFace Chat Target docs

Restrict access to memory databases

PyRIT memory stores every adversarial prompt, model response and score, usually in SQLite on the test host. These records can contain harmful content generated on purpose, so treat the database as sensitive data. Limit file permissions, decide where it lives and how long it is kept, and confirm who may query or copy it. If you move to Azure SQL, apply the same controls through the database's access model.

Check model licenses before loading

Each Hugging Face model carries its own license and usage terms, and some restrict commercial use, redistribution or specific applications. Before a model is loaded locally for testing, record its license, the version tested and any acceptance step the model card requires. Legal or procurement should confirm that testing it, and storing outputs from it, falls within those terms, because the license governs the model rather than PyRIT's MIT license.

Isolate the test host

Local models run arbitrary generation on hardware that also holds your credentials and memory. Place the host in a network segment that cannot reach production systems, restrict outbound traffic to the endpoints you need, and avoid sharing the machine with unrelated workloads. Confirm that any model loaded from a remote source is pinned to a reviewed revision, so the model under test is the one you assessed.

Report PyRIT vulnerabilities privately

If you find a security flaw in PyRIT itself, such as a credential leak through its configuration or memory handling, do not open a public issue. Report it privately to the Microsoft Security Response Center under the project's security policy, as described in the repository README. Keep the reproduction details inside your team until a fix is available, and note the PyRIT version in your report so the maintainers can reproduce it.

PyRIT repository

Common failures when running PyRIT against Hugging Face models

This table lists the failures teams most often hit when running PyRIT's HuggingFaceChatTarget against locally loaded models, with the likely cause and a general fix for each. Use it as a triage checklist before you change model settings, and confirm version-specific behavior against the documentation for the PyRIT and transformers versions you have installed.

FailureLikely causeFix
Model fails to loadModel ID or local path is wrong, the files are incomplete, or the installed library versions do not support the model architectureVerify the model ID or path, re-download the full snapshot, and pin library versions the model card supports before retrying
Out-of-memory on the acceleratorModel weights, precision and context length exceed the GPU memory available, and multi-turn history grows each turnLoad a smaller model or lower precision, shorten the conversation window, and confirm memory requirements for the chosen model before the run
Garbled turns or odd role labelsChat template for the model does not match the template PyRIT applies to the message historyCheck the model's expected chat template, confirm the tokenizer loaded from the same revision, and run a short single-turn smoke test before multi-turn attacks
Token or access errors on gated modelsThe Hugging Face account lacks approval for the gated repository, or the access token is missing, expired or not passed to the processAccept the model terms on the Hub with the account that owns the token, supply the token through your secrets handling, and confirm it is visible to the runtime
Slow multi-turn runsLocal generation runs on a single device, long histories are resent each turn, and concurrency is set higher than the hardware can serveReduce concurrency for local targets, cap history length, and measure per-turn latency on a small objective set before scaling up
Memory records missing turnsRun interrupted before writes completed, a second process wrote to the same SQLite file, or the conversation ID changed between turnsUse one memory database per run, confirm conversation IDs persist across turns, and check stored history against the console transcript after each run

Questions teams ask before testing Hugging Face models with PyRIT

What drives the cost of red teaming a Hugging Face model with PyRIT?

The main drivers are the size of the model, the hardware you have to run it, how many attack strategies you run, which scorer you choose, and how much memory and evidence work the results need. PyRIT itself is open source under the MIT license, so the license adds no fee. What you pay for is people time and compute. Local models need GPU or accelerator capacity for every objective, attack and scoring call, and that capacity recurs for as long as you run tests. Ask any partner quote to break out the one-time setup, the test runs, the scorer work and the reporting, and to state which hardware it assumes.

How long does a PyRIT run against a Hugging Face model take?

Duration depends on the model, the hardware, the number of objectives, the number of turns in each attack and the scorers in use. Multi-turn strategies such as Crescendo, TAP and Skeleton Key make many model calls per objective, so they take much longer than single-turn runs. No duration figure applies to every setup. Measure a small pilot on your own hardware with a few objectives and a single strategy, then scale the plan from the timing you observe. For long scenarios, a hosted endpoint may finish faster than a local model on modest hardware.

Can an internal team run PyRIT against Hugging Face models alone?

Yes, a team with Python experience and access to suitable hardware can install PyRIT with pip and run the HuggingFaceChatTarget on its own. PyRIT's documentation recommends Python 3.13 and supports Python 3.10 up to, but not including, 3.15. The harder parts are choosing objectives and scorers that match your risks, interpreting results, and producing evidence a reviewer will accept. Teams without red teaming experience often do the setup in-house and bring in outside help for the scoring design and the findings review.

What does the client team need to provide for this work?

You need a Python environment, hardware that can load the chosen model, network rules that keep prompts and outputs inside your boundary, and a named owner for the test scope. You also need the list of harms that matter to your business, the model license terms reviewed by someone who can approve them, and a place to store PyRIT memory, which uses SQLite or Azure SQL. Credentials belong in ~/.pyrit/.env and settings in ~/.pyrit/.pyrit_conf, so the team should agree how those files are protected on shared machines.

When is a hosted endpoint a better target than a locally loaded model?

A hosted endpoint is usually the better choice for long multi-turn scenarios where local hardware would make each turn slow, or where you need to test the same deployment your users reach. Local loading through HuggingFaceChatTarget suits smaller models, controlled experiments and cases where prompts must stay on your hardware. Check that the endpoint sits inside your approved network and that its logging and access controls meet your policy before sending test traffic to it.

Should we bring in a partner to red team Hugging Face models with PyRIT?

Outside help is worth considering when you need a scope agreed in writing, test coverage across several attack families, scorer calibration, or a findings report with fixes and a retest. DeployOpen plans, runs and documents security testing of AI systems and prepares evidence for compliance assessments, but it does not issue audit reports or certifications. Most engagements are fixed-scope, with scope, deliverables and timelines agreed before work starts. Ask any provider to show how it will keep the models and results inside your environment.

Which records should we keep so the results hold up in a review?

Keep the model name and version, the PyRIT version, the attack strategy, the objectives used, the scorer and its configuration, and the full conversation records stored in PyRIT memory. Reviewers usually ask how a result was produced, so the run must be repeatable from these records. Store memory and exports under your access controls and retention rules. Note that PyRIT results support evidence work, but an independent auditor decides whether a control is met.

How DeployOpen scopes and delivers PyRIT testing on Hugging Face models

DeployOpen plans and runs PyRIT red teaming against Hugging Face models in infrastructure you control, starting with a written scope that names the models, harms, attack families and evidence you need. The work is delivered as a fixed-scope engagement, with a clear handover of the harness, the results and the operating steps your team keeps.

How we scope

  • Agree in writing which Hugging Face models, local or hosted, are in the objective target set.
  • Define the harm categories, attack strategies and scorers the assessment will and will not cover.
  • Confirm where the models, PyRIT memory and any scoring model will run, and what data may leave that boundary.

How we build

  • Configure the HuggingFace chat target for locally loaded models on hardware you control.
  • Set up a hosted endpoint as the objective target where long multi-turn scenarios need stable availability.
  • Build the PyRIT attack runs, scorers and SQLite or Azure SQL memory configuration, then test them against a known baseline.

How we hand over

  • Deliver the PyRIT configuration, attack scripts and documented target setup for your team to rerun.
  • Provide a findings report with reproduced conversations, scorer results and recommended fixes.
  • Walk your engineers through retesting after model or configuration changes, so the process continues without us.

How we support

  • Engagements are fixed-scope, and the written scope sets the deliverables and timeline before work starts.
  • Ongoing support, PyRIT upgrades and continuous testing are available as a retainer.
  • Confirm the support terms, retest scope and response arrangements in the written scope before signing.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.