# Fine-tune Granite Time Series
Source: https://wwwpoc.ibm.com/granite/docs/fine-tune/time-series
Learn how to fine-tune Granite Time Series models
## Overview
In order to be generally applicable to many time series datasets, the pretrained
Granite-TimeSeries model is trained in a channel independent way. Under channel
independence, the model learns a common dynamics model across all channels
without considering interactions. In many cases, there is important information
in a time series dataset related to how different channels interact with each
other. In order to capture these dependencies, we need to fine tune and enable
channel mixing in the decoder.
The fine-tuning process requires the following steps:
1. Load and prepare data using the time series preprocessor. Since we are
fine-tuning the model, we have more options to include things like
cross-channel interactions, exogenous features and categorical values.
2. Load the model and freeze the backbone
3. Create a Hugging Face Trainer and train the model
4. Evaluate the model
For the example code-snippets below, we assume that a dataset is available with
a timestamp column ("date"), and three value columns ("value1", "value2",
"value3"). The columns "value1" and "value2" will serve as targets of the
forecasting exercise, while the "value3" column will serve as a control column.
A control column is a type of exogenous column where it is assumed that its
value is known into the future.
## Prerequisites
Please make sure your python environment is properly set up. The code snippets
below are illustrative examples of how various components work with our
Granite-TimeSeries models, and require the installation of the
[Granite TSFM library](https://github.com/ibm-granite/granite-tsfm). Please
[see the setup instructions](/run/granite-on-mac/time-series).
## Data loading
Pandas dataframes are required in the preprocessing and forecasting pipeline
components. We simply read the csv into a pandas dataframe, making sure to
format the timestamp column properly.
```python Python theme={null}
data = pd.read_csv(
dataset_path,
parse_dates=["date"],
)
```
## Data preparation
In the zero-shot case, we can only handle datasets with id columns and one or
more target columns, advanced use cases involving exogenous or categorical
features are not yet supported. In the fine-tuning case, we are free to specify
additional columns, like control\_columns. We first specify the parameters of the
preprocessor, enabling scaling (normalization) of the data. Then we use the
preprocessor to extract train, validation, and test datasets from the original
data.
```python Python theme={null}
tsp = TimeSeriesPreprocessor(
id_columns=[],
timestamp_column="date"
target_columns=["value1", "value2"],
control_columns=["value3"],
prediction_length=96,
context_length=512,
scaling=True,
scaling_type="standard",
)
dset_train, dset_valid, dset_test = get_datasets(tsp, data, split_config={"train": 0.6, "test": 0.2})
```
## Loading the pretrained granite time series model
Here we load the model using `from_pretrained` but pass some extra configuration
arguments. Note the presence of "decoder\_mode" and the other index related
arguments. The TimeSeriesPreprocessor provides some helper functions to make
passing these parameters easier.
```python Python theme={null}
model = TinyTimeMixerForPrediction.from_pretrained(
"ibm-granite/granite-timeseries-ttm-r2",
num_input_channels=tsp.num_input_channels,
prediction_channel_indices=tsp.prediction_channel_indices,
exogenous_channel_indices=tsp.exogenous_channel_indices,
decoder_mode="mix_channel"
)
for param in model.backbone.parameters():
param.requires_grad = False
```
The key here is the "mix-channel" decoder mode. This enables the decoder to
consider inter-channel dependencies.
## Creating a Hugging Face trainer and training the model
We create a Hugging Face Trainer, passing the train and validation datasets that
were created earlier. The first step is to define the training arguments:
```python Python theme={null}
finetune_forecast_args = TrainingArguments(
output_dir="train_output",
overwrite_output_dir=True,
learning_rate=0.001,
num_train_epochs=100,
do_eval=True,
evaluation_strategy="epoch",
per_device_train_batch_size=64,
per_device_eval_batch_size=64,
dataloader_num_workers=8,
report_to=None,
save_strategy="epoch",
logging_strategy="epoch",
save_total_limit=1,
logging_dir="train_logs",
load_best_model_at_end=True,
metric_for_best_model="eval_loss",
greater_is_better=False,
)
```
Many of the arguments above, e.g., learning rate, batch size, are dataset
specific and will need to be adjusted for your specific use case. Next we define
the callbacks. We add early stopping, which stops training when no improvement
is seen, and a tracking callback, which reports training time statistics.
```python Python theme={null}
early_stopping_callback = EarlyStoppingCallback(
early_stopping_patience=10, # Number of epochs with no improvement after which to stop
early_stopping_threshold=0.0, # Minimum improvement required to consider as improvement
)
tracking_callback = TrackingCallback()
```
Next we create the optimizer and the learning rate scheduler. We use AdamW as
the optimizer and the 1cycle learning rate policy which adapts the learning rate
quickly.
```python Python theme={null}
optimizer = AdamW(finetune_forecast_model.parameters(), lr=learning_rate)
scheduler = OneCycleLR(
optimizer,
learning_rate,
epochs=num_epochs,
steps_per_epoch=math.ceil(len(dset_train) / (batch_size)),
)
```
Finally, we construct the trainer, using the components we created above:
```python Python theme={null}
finetune_forecast_trainer = Trainer(
model=model,
args=finetune_forecast_args,
train_dataset=dset_train,
eval_dataset=dset_val,
callbacks=[early_stopping_callback, tracking_callback],
optimizers=(optimizer, scheduler),
)
finetune_forecast_trainer.train()
```
## Evaluating the fine-tuned model
We make use of the trainer to evaluate on the test dataset created earlier. In
the output of the command below "eval\_loss" refers to the mean squared error on
the normalized test data.
```python Python theme={null}
fewshot_output = finetune_forecast_trainer.evaluate(dset_test)
```
Explore sample code in a GitHub repo
Execute sample code in Colab
# Fine-tune Granite using Unsloth
Source: https://wwwpoc.ibm.com/granite/docs/fine-tune/unsloth
Train Granite with Unsloth, an open-source framework for LLM fine-tuning and reinforcement learning.
Train, run, evaluate and save Granite and other LLMs 2x faster with 70% less VRAM.
Explore sample code in a GitHub repo
Execute sample code in Colab
# Naming Guidance
Source: https://wwwpoc.ibm.com/granite/docs/model-standards/naming-guidance
Guidance for naming derivatives of Granite models.
If you release a derivative of Granite, please label derivatives with your entity name at the beginning, followed by “Granite,” and then adding any further model descriptors for your modified model at the end: e.g. `acme-Granite-reasoning`.
If possible, attaching the notices file to the Granite model or its download site would be appreciated: `NOTICE.txt`.
***
This model is part of the Granite family of foundation models developed by International Business Machines Corporation (IBM).\
"GRANITE" is a registered trademark of International Business Machines Corporation (IBM) in the United States and/or other countries. Use of the Granite name in derivative works must not imply IBM authorship, endorsement, or affiliation unless explicitly stated.
License
Apache License, Version 2.0\
You may use, modify, and distribute this model in accordance with the terms of that license.
To help others understand your model’s lineage
If you create and distribute a derivative of a Granite model, please label derivatives with your entity name at the beginning, followed by “Granite,” and then adding any further model descriptors for your modified model at the end: e.g. `acme-Granite-reasoning`.\
Include the full model base name (e.g., `Granite-3.3-8B-Instruct`) in documentation or metadata.\
Avoid using "Granite" alone in your project title to prevent confusion with official IBM releases.
***
For more information about the Granite model family, visit:
* [https://www.ibm.com/granite](https://www.ibm.com/granite)
* [https://huggingface.co/ibm-granite](https://huggingface.co/ibm-granite)
# Signature Verification
Source: https://wwwpoc.ibm.com/granite/docs/model-standards/signature-verification
Instructions for verifying model signatures.
Model signing is an experimental feature with ongoing development, which might include breaking changes. We are releasing these capabilities to improve the integrity of our models for our security-conscious users and to facilitate feedback from the community.
***
## Getting started
Before trying to verify the signature, ensure that the tensor files have been downloaded with git-lfs and that no files have been added, removed, or modified in your local git checkout:
```bash theme={null}
git lfs fetch --all
git lfs pull
git lfs checkout
```
Install the model\_signing (v1.0.1) library with the following command:
```bash theme={null}
pip install 'model-signing==v1.1.1'
```
***
## Signature verification
Then verify the signature with the following command ensuring that the IBM identity '[granite.preview@ibm.com](mailto:granite.preview@ibm.com)' was used for signing this model:
```bash theme={null}
python -m model_signing verify sigstore \
--signature model.sig \
--ignore-paths .git \
--ignore-paths .gitattributes \
--identity Granite.Preview@ibm.com \
--identity_provider https://sigstore.verify.ibm.com/oauth2 \
.
```
# Granite Docling
Source: https://wwwpoc.ibm.com/granite/docs/models/docling
View the full Granite Docling collection on Hugging Face
Try out the Granite Docling Demo on Hugging Face
## Overview
The **Granite Docling** model is designed for enterprise applications that involve end-to-end document understanding and conversion. Unlike traditional pipelines that chain together OCR, layout analysis, and post-processing, Docling integrates vision and language into a single compact model (\~ 258M parameters), capable of parsing PDFs, slides, and scanned pages directly into structured, machine-readable formats.
A key feature is its use of DocTags, a purpose-built markup language that separates content from layout while faithfully preserving tables, code blocks, inline and block math, and document hierarchy. This design improves fidelity, minimizes errors in reading order and structure, and makes outputs well-suited for downstream tasks such as retrieval-augmented generation (RAG) and fine-tuning. While optimized for Latin-script documents, it also offers early support for Japanese, Chinese, and Arabic.
Granite Docling is released under the Apache 2.0 license, ensuring it is freely available for both research and commercial use. It complements the open-source Docling library by providing an all-in-one, production-ready alternative for document conversion, with full transparency into its design and training.
## Getting Started
The easiest way to use this model is through the [🐥Docling](https://github.com/docling-project/docling) library. It will automatically download this model and convert documents to various formats for you.
Install the latest version of docling through pip, then use the following CLI command:
```python Python theme={null}
# Convert to HTML and Markdown:
docling --to html --to md --pipeline vlm --vlm-model granite_docling "https://arxiv.org/pdf/2501.17887" # accepts files, urls or directories
# Convert to HTML including layout visualization:
docling --to html_split_page --show-layout --pipeline vlm --vlm-model granite_docling "https://arxiv.org/pdf/2501.17887"
```
You can also set this model up within the Docling SDK:
```python Python theme={null}
from docling.datamodel import vlm_model_specs
from docling.datamodel.base_models import InputFormat
from docling.datamodel.pipeline_options import (
VlmPipelineOptions,
)
from docling.document_converter import DocumentConverter, PdfFormatOption
from docling.pipeline.vlm_pipeline import VlmPipeline
source = "https://arxiv.org/pdf/2501.17887"
###### USING SIMPLE DEFAULT VALUES
# - GraniteDocling model
# - Using the transformers framework
converter = DocumentConverter(
format_options={
InputFormat.PDF: PdfFormatOption(
pipeline_cls=VlmPipeline,
),
}
)
doc = converter.convert(source=source).document
print(doc.export_to_markdown())
###### USING MACOS MPS ACCELERATOR
# For more options see the compare_vlm_models.py example.
pipeline_options = VlmPipelineOptions(
vlm_options=vlm_model_specs.GRANITEDOCLING_MLX,
)
converter = DocumentConverter(
format_options={
InputFormat.PDF: PdfFormatOption(
pipeline_cls=VlmPipeline,
pipeline_options=pipeline_options,
),
}
)
doc = converter.convert(source=source).document
print(doc.export_to_markdown())
```
Alternatively, you can use bare transformers, vLLM, onnx or mlx-vlm to perform inference, and docling-core APIs to convert results to variety of output formats (md, html, etc.).
Here's an example of single-page image inference using plain transformers.
```python Python theme={null}
# Prerequisites:
# pip install torch
# pip install docling_core
# pip install transformers
import torch
from docling_core.types.doc import DoclingDocument
from docling_core.types.doc.document import DocTagsDocument
from transformers import AutoProcessor, AutoModelForVision2Seq
from transformers.image_utils import load_image
from pathlib import Path
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
# Load images
image = load_image("https://huggingface.co/ibm-granite/granite-docling-258M/resolve/main/assets/new_arxiv.png")
# Initialize processor and model
processor = AutoProcessor.from_pretrained("ibm-granite/granite-docling-258M")
model = AutoModelForVision2Seq.from_pretrained(
"ibm-granite/granite-docling-258M",
torch_dtype=torch.bfloat16,
_attn_implementation="flash_attention_2" if DEVICE == "cuda" else "sdpa",
).to(DEVICE)
# Create input messages
messages = [
{
"role": "user",
"content": [
{"type": "image"},
{"type": "text", "text": "Convert this page to docling."}
]
},
]
# Prepare inputs
prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
inputs = processor(text=prompt, images=[image], return_tensors="pt")
inputs = inputs.to(DEVICE)
# Generate outputs
generated_ids = model.generate(**inputs, max_new_tokens=8192)
prompt_length = inputs.input_ids.shape[1]
trimmed_generated_ids = generated_ids[:, prompt_length:]
doctags = processor.batch_decode(
trimmed_generated_ids,
skip_special_tokens=False,
)[0].lstrip()
print(f"DocTags: \n{doctags}\n")
# Populate document
doctags_doc = DocTagsDocument.from_doctags_and_image_pairs([doctags], [image])
# create a docling document
doc = DoclingDocument.load_from_doctags(doctags_doc, document_name="Document")
print(f"Markdown:\n{doc.export_to_markdown()}\n")
## export as any format.
# Path("out/").mkdir(parents=True, exist_ok=True)
# HTML:
# output_path_html = Path("out/") / "example.html"
# doc.save_as_html(output_path_html)
# Markdown:
# output_path_md = Path("out/") / "example.md"
# doc.save_as_markdown(output_path_md)
```
Here's an example of fast batch inference using vLLM:
```python Python theme={null}
# Prerequisites:
# pip install vllm
# pip install docling_core
# place page images you want to convert into "img/" dir
import time
import os
from vllm import LLM, SamplingParams
from transformers import AutoProcessor
from PIL import Image
from docling_core.types.doc import DoclingDocument
from docling_core.types.doc.document import DocTagsDocument
from pathlib import Path
# Configuration
MODEL_PATH = "ibm-granite/granite-docling-258M"
IMAGE_DIR = "img/" # Place your page images here
OUTPUT_DIR = "out/"
PROMPT_TEXT = "Convert this page to docling."
messages = [
{
"role": "user",
"content": [
{"type": "image"},
{"type": "text", "text": PROMPT_TEXT},
],
},
]
# Ensure output directory exists
os.makedirs(OUTPUT_DIR, exist_ok=True)
# Initialize LLM
llm = LLM(model=MODEL_PATH, revision="untied", limit_mm_per_prompt={"image": 1})
processor = AutoProcessor.from_pretrained(MODEL_PATH)
sampling_params = SamplingParams(
temperature=0.0,
max_tokens=8192,
skip_special_tokens=False,
)
# Load and prepare all images and prompts up front
batched_inputs = []
image_names = []
for img_file in sorted(os.listdir(IMAGE_DIR)):
if img_file.lower().endswith((".png", ".jpg", ".jpeg")):
img_path = os.path.join(IMAGE_DIR, img_file)
with Image.open(img_path) as im:
image = im.convert("RGB")
prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
batched_inputs.append({"prompt": prompt, "multi_modal_data": {"image": image}})
image_names.append(os.path.splitext(img_file)[0])
# Run batch inference
start_time = time.time()
outputs = llm.generate(batched_inputs, sampling_params=sampling_params)
# Postprocess all results
for img_fn, output, input_data in zip(image_names, outputs, batched_inputs):
doctags = output.outputs[0].text
output_path_dt = Path(OUTPUT_DIR) / f"{img_fn}.dt"
output_path_md = Path(OUTPUT_DIR) / f"{img_fn}.md"
with open(output_path_dt, "w", encoding="utf-8") as f:
f.write(doctags)
# Convert to DoclingDocument and save markdown
doctags_doc = DocTagsDocument.from_doctags_and_image_pairs([doctags], [input_data["multi_modal_data"]["image"]])
doc = DoclingDocument.load_from_doctags(doctags_doc, document_name="Document")
doc.save_as_markdown(output_path_md)
print(f"Total time: {time.time() - start_time:.2f} sec")
```
# Granite Embedding
Source: https://wwwpoc.ibm.com/granite/docs/models/embedding
View the full Granite Embedding collection on Hugging Face
Download and run Granite Embedding with Ollama
Deploy Granite Embedding on Replicate
## Overview
The **Granite Embedding** model collection consists of embedding models to generate high-quality text embeddings and a reranker model to improve the relevance and quality of search results or recommendations. The embedding models output vector representations (aka embeddings) of textual inputs such as queries, passages, and documents to capture the semantic meaning of the input text. The primary use cases for these embeddings are in semantic search and retrieval-augmented generation (RAG) applications.
The **Granite Embedding Reranker** model is optional, but useful to further improve the relevance and quality of search results or recommendations. After the initial retrieval of items based on their embeddings, the reranker refines the ranking by considering additional factors and more complex criteria.
Built on a foundation of carefully curated, permissibly licensed public datasets, the Granite Embedding models achieve state-of-the-art results in their respective weight classes. On the [MTEB Leaderboard](https://huggingface.co/spaces/mteb/leaderboard), **granite-embedding-97m-multilingual-r2 ranks #1** for multilingual embedding models under 100M parameters, and **granite-embedding-311m-multilingual-r2 ranks #2** for multilingual embedding models under 500M parameters.
Granite Embedding models are released under the Apache 2.0 license, making them freely available for both research and commercial purposes, with full transparency into their training data.
[Granite Embedding Paper](https://arxiv.org/abs/2508.21085)
## Getting Started
### Intended Use
The Granite Embedding 311m multilingual model is designed to produce fixed-length vector representations for a given text, which can be used for text similarity, retrieval, and search applications across multiple languages. It supports 200+ languages with enhanced support for 52 languages.
For efficient inference, these models support Flash Attention 2. Installing it is optional but can lead to faster encoding:
```bash Install theme={null}
pip install flash_attn
```
### Usage with Sentence Transformers
The model is compatible with the SentenceTransformer library and is very easy to use:
First, install the sentence transformers library:
```bash Install theme={null}
pip install sentence_transformers
```
The model can then be used to encode pairs of text and find the similarity between their representations:
```python Python theme={null}
from sentence_transformers import SentenceTransformer, util
model_path = "ibm-granite/granite-embedding-311m-multilingual-r2"
# Load the Sentence Transformer model
model = SentenceTransformer(model_path)
input_queries = [
'What is the tallest mountain in Japan?', # English query
'Wer hat das Lied Achy Breaky Heart geschrieben?', # German query
'ドイツの首都はどこですか?', # Japanese query
]
input_passages = [
"富士山は、静岡県と山梨県にまたがる活火山で、標高3776.12 mで日本最高峰の独立峰である。", # Japanese passage
"Achy Breaky Heart is a country song written by Don Von Tress. Originally titled Don't Tell My Heart and performed by The Marcy Brothers in 1991.", # English passage
"Berlin ist die Hauptstadt und ein Land der Bundesrepublik Deutschland. Die Stadt ist mit rund 3,7 Millionen Einwohnern die bevölkerungsreichste Kommune Deutschlands.", # German passage
]
# Cross-lingual retrieval: each query should score highest with its matching passage in a different language
query_embeddings = model.encode(input_queries)
passage_embeddings = model.encode(input_passages)
# calculate cosine similarity — expect high scores on the diagonal (EN→JA, DE→EN, JA→DE)
print(util.cos_sim(query_embeddings, passage_embeddings))
# output: tensor([[0.9393, 0.6899, 0.7627],
# [0.6780, 0.9598, 0.7062],
# [0.7818, 0.7342, 0.9172]])
```
### Matryoshka Representation Learning
This model supports Matryoshka Representation Learning (MRL), which allows you to truncate embeddings to smaller dimensions (e.g., 512, 256, 128) with graceful performance degradation. This is useful for reducing storage and memory requirements.
```python Python theme={null}
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("ibm-granite/granite-embedding-311m-multilingual-r2")
# Full 768-dimensional embeddings
full_embeddings = model.encode(["example text"])
print(full_embeddings.shape) # (1, 768)
# Truncated to 256 dimensions — still effective for many retrieval tasks
truncated_embeddings = model.encode(["example text"], truncate_dim=256)
print(truncated_embeddings.shape) # (1, 256)
```
### Usage with Hugging Face Transformers
This is a simple example of how to use the granite-embedding-311m-multilingual-r2 model with the Transformers library and PyTorch. For a complete retrieval workflow including passage encoding and cosine similarity, see the Sentence Transformers example above.
First, install the required libraries:
```bash Install theme={null}
pip install transformers torch
```
The model can then be used to encode text:
```python Python theme={null}
import torch
from transformers import AutoModel, AutoTokenizer
model_path = "ibm-granite/granite-embedding-311m-multilingual-r2"
# Load the model and tokenizer
model = AutoModel.from_pretrained(model_path)
tokenizer = AutoTokenizer.from_pretrained(model_path)
model.eval()
input_queries = [
'What is the tallest mountain in Japan?', # English query
'Wer hat das Lied Achy Breaky Heart geschrieben?', # German query
'ドイツの首都はどこですか?', # Japanese query
]
# tokenize inputs
tokenized_queries = tokenizer(input_queries, padding=True, truncation=True, return_tensors='pt')
# encode queries
with torch.no_grad():
model_output = model(**tokenized_queries)
# Perform pooling. granite-embedding-311m-multilingual-r2 uses CLS Pooling
query_embeddings = model_output[0][:, 0]
# normalize the embeddings
query_embeddings = torch.nn.functional.normalize(query_embeddings, dim=1)
```
### Optimized Inference and Deployment
#### ONNX and OpenVINO
Pre-converted ONNX and OpenVINO models are released alongside the PyTorch weights for production deployment. These can be loaded through the Optimum library:
```python Python theme={null}
pip install langchain_huggingface sentence_transformers \
langchain_milvus 'pymilvus[milvus_lite]' \
langchain_community \
langchain_text_splitters \
wget
```
The ONNX model is compatible with any ONNX Runtime backend (CPU, CUDA, TensorRT, DirectML). The OpenVINO model is optimized for Intel hardware including CPUs and integrated GPUs.
#### vLLM
The model can be served as an embedding endpoint using vLLM:
```python Python theme={null}
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_milvus import Milvus
from langchain_community.document_loaders import TextLoader
from langchain_text_splitters import CharacterTextSplitter
import os, tempfile, wget
# load the embedding model
embeddings_model = HuggingFaceEmbeddings(model_name="ibm-granite/granite-embedding-30m-english")
# setup the vectordb
db_file = tempfile.NamedTemporaryFile(prefix="milvus_", suffix=".db", delete=False).name
print(f"The vector database will be saved to {db_file}")
vector_db = Milvus(
embedding_function=embeddings_model,
connection_args={"uri": db_file},
auto_id=True,
index_params={"index_type": "AUTOINDEX"},
)
# load example corpus file
filename = 'state_of_the_union.txt'
url = 'https://raw.github.com/IBM/watson-machine-learning-samples/master/cloud/data/foundation_models/state_of_the_union.txt'
if not os.path.isfile(filename):
wget.download(url, out=filename)
loader = TextLoader(filename)
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=0)
texts = text_splitter.split_documents(documents)
# add processed documents to the vectordb
vector_db.add_documents(texts)
# search the vectordb with the query
query = "What did the president say about Ketanji Brown Jackson"
docs = vector_db.similarity_search(query)
print(docs[0].page_content)
```
# Granite 4.0
Source: https://wwwpoc.ibm.com/granite/docs/models/granite
View model details on Hugging Face
Leverage Granite to search the web and write research reports
Download and run Granite locally with Ollama
Check out these recipes to start using Granite
## Overview
Granite 4.0 introduces a hybrid Mamba-2/transformer architecture, with a Mixture-of-Experts (MoE) strategy in select models, delivering more than 70% lower memory requirements and 2x faster inference speeds compared to similar models, particularly in multi-session and long-context scenarios. The models deliver strong performance across benchmarks, with Granite 4.0 Small achieving industry-leading results in key agentic tasks like instruction following and function calling. These efficiencies make the models well-suited for a wide range of use cases like retrieval-augmented generation (RAG), multi-agent workflows, and edge deployments. Granite 4.0 is released under Apache 2.0, cryptographically signed for authenticity, and the first open model family certified under ISO 42001.
Granite 4.0 Release Blog
Granite 4.0 Nano Release Blog
| Model |
Architecture Type |
Model Size |
Intended Use |
Granite-4.0-H-Small
|
Hybrid, Mixture of Experts |
32B total / 9B activated |
Workhorse model for key enterprise tasks like RAG and agents |
Granite-4.0-H-Tiny
|
Hybrid, Mixture of Experts |
7B total / 1B activated |
Designed for low latency and local applications, particularly where the task has long prefill or other scenarios where a MoE model is desired |
Granite-4.0-H-Micro
|
Hybrid, Dense |
3B total |
Designed for low latency and local applications, and as a building block to perform key tasks (like function calling) quickly within agentic workflows |
Granite-4.0-Micro
|
Traditional, Dense |
3B total |
Alternative option for users when Mamba2 support is not yet optimized (e.g. llama.cpp, PEFT, etc) |
Granite-4.0-H-1B
|
Dense, Hybrid |
1.5B |
Ideal models for edge, on-device, and latency-sensitive use cases |
Granite-4.0-1B
|
Dense, Traditional |
1B |
Alternative option for users when Mamba2 support is not yet optimized (e.g. llama.cpp, PEFT, etc) |
Granite-4.0-H-350M
|
Dense, Hybrid |
350M |
Similar use cases as Granite-4.0-H-1B, but even smaller and cheaper to run |
Granite-4.0-350M
|
Dense, Traditional |
350M |
Alternative option for users when Mamba2 support is not yet optimized (e.g. llama.cpp, PEFT, etc) |
## Inference Examples
### Basic Inference
```python transformers theme={null}
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
device = "cuda"
model_path = "ibm-granite/granite-4.0-h-tiny"
tokenizer = AutoTokenizer.from_pretrained(model_path)
# drop device_map if running on CPU
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
model.eval()
# change input text as desired
chat = [
{ "role": "user", "content": "What is the largest ocean on Earth?"},
]
chat = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
# tokenize the text
input_tokens = tokenizer(chat, return_tensors="pt").to(device)
# generate output tokens
output = model.generate(**input_tokens,
max_new_tokens=150, temperature=0)
# decode output tokens into text
output = tokenizer.batch_decode(output)
print(output[0])
```
```python watsonx.ai theme={null}
### This snippet assumes watsonx.ai access.
### If not already setup, follow the guide here:
### https://github.com/ibm-granite-community/granite-kitchen/blob/main/recipes/Getting_Started/Getting_Started_with_WatsonX.ipynb
import requests
import json
WATSONX_APIKEY = "WATSONX_APIKEY" # Replace with your watsonx.ai API key
WATSONX_PROJECT_ID = "WATSONX_PROJECT_ID" # Replace with your watsonx.ai project id
# STEP 1: Retrieve bearer token using WATSONX_APIKEY
token_url = "https://iam.cloud.ibm.com/oidc/token"
token_data = {
"grant_type": "urn:ibm:params:oauth:grant-type:apikey",
"apikey": WATSONX_APIKEY,
}
token_headers = {"Content-Type": "application/x-www-form-urlencoded"}
token_response = requests.post(token_url, data=token_data, headers=token_headers)
if token_response.status_code != 200:
raise Exception("Failed to retrieve token: " + token_response.text)
access_token = token_response.json()["access_token"]
# STEP 2: Setup call to the chat endpoint in watsonx.ai
url = "https://us-south.ml.cloud.ibm.com/ml/v1/text/chat?version=2025-10-25"
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": f"Bearer {access_token}",
}
body = {
"messages": [{"role": "user", "content": "What is the largest ocean on Earth?"}],
"project_id": WATSONX_PROJECT_ID,
"model_id": "ibm/granite-4-h-small",
"max_completion_tokens": 2000,
"temperature": 0,
}
# STEP 3: Execute call to the chat endpoint in watsonx.ai
response = requests.post(url, headers=headers, json=body)
if response.status_code != 200:
raise Exception("Non-200 response: " + str(response.text))
data = response.json()
print(json.dumps(data, indent=4))
```
```python OpenAI API theme={null}
### This snippet assumes access to an OpenAI compatible endpoint
### If not already setup, an example setup can be achieved
### through vLLM. Follow the guide here:
### https://www.ibm.com/granite/docs/run/granite-with-vllm-containerized
import requests
import json
# STEP 1: Setup call to the OpenAI compatible endpoint
url = "/chat/completions"
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
}
body = {
"messages": [{"role": "user", "content": "What is the largest ocean on Earth?"}],
"model_id": "ibm-granite/granite-4.0-h-small",
"max_completion_tokens": 2000,
"temperature": 0,
}
# STEP 2: Execute call to the chat endpoint
response = requests.post(url, headers=headers, json=body)
if response.status_code != 200:
raise Exception("Non-200 response: " + str(response.text))
data = response.json()
print(json.dumps(data, indent=4))
```
```text Chat Template theme={null}
<|start_of_role|>user<|end_of_role|>What is the largest ocean on Earth?<|end_of_text|>
<|start_of_role|>assistant<|end_of_role|>The largest ocean on Earth is the Pacific Ocean. It covers an area of about 63.8 million square miles (165.25 million square kilometers), which is more than twice the size of the second-largest ocean, the Atlantic Ocean. The Pacific Ocean lies between the Americas to the east and Asia and Australia to the west.<|end_of_text|>
```
The Granite 4 models work best with temperature set to 0 for most inferencing
tasks.
### Tool calling
```python Transformers theme={null}
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
device = "cuda"
# model_path = ""
model_path = "ibm-granite/granite-4.0-micro"
tokenizer = AutoTokenizer.from_pretrained(model_path)
# drop device_map if running on CPU
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
model.eval()
chat=[
{"role": "user", "content": "What's the current weather in New York?"},
{"role": "assistant",
"content": "",
"tool_calls": [
{
"function": {
"name": "get_current_weather",
"arguments": {"city": "New York"}
}
}
]
},
{"role": "tool", "content": "New York is sunny with a temperature of 30°C."},
{"role": "user", "content": "OK, Now tell me what's the weather like in Bengaluru at this moment?"}
]
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather",
"parameters": {
"type": "object",
"properties": {
"location" : {
"description": "The city and state, e.g. San Francisco, CA",
"type": "string",
},
},
"required" : ["location"]
}
}
},
{
"type": "function",
"function": {
"name": "get_stock_price",
"description": "Retrieves the current stock price for a given ticker symbol. The ticker symbol must be a valid symbol for a publicly traded company on a major US stock exchange like NYSE or NASDAQ. The tool will return the latest trade price in USD. It should be used when the user asks about the current or most recent price of a specific stock. It will not provide any other information about the stock or company.",
"parameters": {
"type": "object",
"properties": {
"ticker" : {
"description": "The stock ticker symbol, e.g. AAPL for Apple Inc.",
"type": "string",
},
}
}
}
}
]
chat = tokenizer.apply_chat_template(chat,tokenize=False, add_generation_prompt=True, tools=tools)
# tokenize the text
input_tokens = tokenizer(chat, return_tensors="pt").to(device)
# generate output tokens
output = model.generate(**input_tokens,
max_new_tokens=100, temperature=0)
# decode output tokens into text
output = tokenizer.batch_decode(output)
# print output
print(output[0])
```
```python watsonx.ai theme={null}
### This snippet assumes watsonx.ai access.
### If not already setup, follow the guide here:
### https://github.com/ibm-granite-community/granite-kitchen/blob/main/recipes/Getting_Started/Getting_Started_with_WatsonX.ipynb
import requests
import json
WATSONX_APIKEY = "WATSONX_APIKEY" # Replace with your watsonx.ai API key
WATSONX_PROJECT_ID = "WATSONX_PROJECT_ID" # Replace with your watsonx.ai project id
# STEP 1: Retrieve bearer token using WATSONX_APIKEY
token_url = "https://iam.cloud.ibm.com/oidc/token"
token_data = {
"grant_type": "urn:ibm:params:oauth:grant-type:apikey",
"apikey": WATSONX_APIKEY,
}
token_headers = {"Content-Type": "application/x-www-form-urlencoded"}
token_response = requests.post(token_url, data=token_data, headers=token_headers)
if token_response.status_code != 200:
raise Exception("Failed to retrieve token: " + token_response.text)
access_token = token_response.json()["access_token"]
# STEP 2: Setup call to the chat endpoint in watsonx.ai
url = "https://us-south.ml.cloud.ibm.com/ml/v1/text/chat?version=2025-10-25"
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": f"Bearer {access_token}",
}
chat = [
{"role": "user", "content": "What's the current weather in New York?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "chatcmpl-tool-a5ecf628c4fd4be3995cadb1ba13c8ad",
"type": "function",
"function": {
"name": "get_current_weather",
"arguments": '{"city": "New York"}',
},
}
],
},
{
"role": "tool",
"content": "New York is sunny with a temperature of 30°C.",
"tool_call_id": "chatcmpl-tool-a5ecf628c4fd4be3995cadb1ba13c8ad",
},
{
"role": "user",
"content": "OK, Now tell me what's the weather like in Bengaluru at this moment?",
},
]
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather",
"parameters": {
"type": "object",
"properties": {
"location": {
"description": "The city and state, e.g. San Francisco, CA",
"type": "string",
},
},
"required": ["location"],
},
},
},
{
"type": "function",
"function": {
"name": "get_stock_price",
"description": "Retrieves the current stock price for a given ticker symbol. The ticker symbol must be a valid symbol for a publicly traded company on a major US stock exchange like NYSE or NASDAQ. The tool will return the latest trade price in USD. It should be used when the user asks about the current or most recent price of a specific stock. It will not provide any other information about the stock or company.",
"parameters": {
"type": "object",
"properties": {
"ticker": {
"description": "The stock ticker symbol, e.g. AAPL for Apple Inc.",
"type": "string",
},
},
},
},
},
]
body = {
"messages": chat,
"tools": tools,
"project_id": WATSONX_PROJECT_ID,
"model_id": "ibm/granite-4-h-small",
"max_completion_tokens": 2000,
"temperature": 0,
}
# STEP 3: Execute call to the chat endpoint in watsonx.ai
response = requests.post(url, headers=headers, json=body)
if response.status_code != 200:
raise Exception("Non-200 response: " + str(response.text))
data = response.json()
print(json.dumps(data, indent=4))
```
```python OpenAI API theme={null}
### This snippet assumes access to an OpenAI compatible endpoint
### If not already setup, an example setup can be achieved
### through vLLM. Follow the guide here:
### https://www.ibm.com/granite/docs/run/granite-with-vllm-containerized
import requests
import json
# STEP 1: Setup call to the OpenAI compatible endpoint
url = "/chat/completions"
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
}
chat = [
{"role": "user", "content": "What's the current weather in New York?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "chatcmpl-tool-a5ecf628c4fd4be3995cadb1ba13c8ad",
"type": "function",
"function": {
"name": "get_current_weather",
"arguments": '{"city": "New York"}',
},
}
],
},
{
"role": "tool",
"content": "New York is sunny with a temperature of 30°C.",
"tool_call_id": "chatcmpl-tool-a5ecf628c4fd4be3995cadb1ba13c8ad",
},
{
"role": "user",
"content": "OK, Now tell me what's the weather like in Bengaluru at this moment?",
},
]
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather",
"parameters": {
"type": "object",
"properties": {
"location": {
"description": "The city and state, e.g. San Francisco, CA",
"type": "string",
},
},
"required": ["location"],
},
},
},
{
"type": "function",
"function": {
"name": "get_stock_price",
"description": "Retrieves the current stock price for a given ticker symbol. The ticker symbol must be a valid symbol for a publicly traded company on a major US stock exchange like NYSE or NASDAQ. The tool will return the latest trade price in USD. It should be used when the user asks about the current or most recent price of a specific stock. It will not provide any other information about the stock or company.",
"parameters": {
"type": "object",
"properties": {
"ticker": {
"description": "The stock ticker symbol, e.g. AAPL for Apple Inc.",
"type": "string",
},
},
},
},
},
]
body = {
"messages": chat,
"tools": tools,
"model_id": "ibm-granite/granite-4.0-h-small",
"max_completion_tokens": 2000,
"temperature": 0,
}
# STEP 2: Execute call to the chat endpoint
response = requests.post(url, headers=headers, json=body)
if response.status_code != 200:
raise Exception("Non-200 response: " + str(response.text))
data = response.json()
print(json.dumps(data, indent=4))
```
```text Chat Template theme={null}
<|start_of_role|>system<|end_of_role|>You are a helpful assistant with access to the following tools. You may call one or more tools to assist with the user query.
You are provided with function signatures within XML tags:
{"type": "function", "function": {"name": "get_current_weather", "description": "Get the current weather", "parameters": {"type": "object", "properties": {"location": {"description": "The city and state, e.g. San Francisco, CA", "type": "string"}}, "required": ["location"]}}}
{"type": "function", "function": {"name": "get_stock_price", "description": "Retrieves the current stock price for a given ticker symbol. The ticker symbol must be a valid symbol for a publicly traded company on a major US stock exchange like NYSE or NASDAQ. The tool will return the latest trade price in USD. It should be used when the user asks about the current or most recent price of a specific stock. It will not provide any other information about the stock or company.", "parameters": {"type": "object", "properties": {"ticker": {"description": "The stock ticker symbol, e.g. AAPL for Apple Inc.", "type": "string"}}}}}
For each tool call, return a json object with function name and arguments within XML tags:
{"name": , "arguments": }
. If a tool does not exist in the provided list of tools, notify the user that you do not have the ability to fulfill the request.<|end_of_text|>
<|start_of_role|>user<|end_of_role|>What's the current weather in New York?<|end_of_text|>
<|start_of_role|>assistant<|end_of_role|>
{"name": "get_current_weather", "arguments": {"city": "New York"}}
<|end_of_text|>
<|start_of_role|>user<|end_of_role|>
New York is sunny with a temperature of 30°C.
<|end_of_text|>
<|start_of_role|>user<|end_of_role|>OK, Now tell me what's the weather like in Bengaluru at this moment?<|end_of_text|>
<|start_of_role|>assistant<|end_of_role|>
{"name": "get_current_weather", "arguments": {"city": "Bengaluru"}}
<|end_of_text|>
```
Consider the following points to build prompts for tool-calling tasks:
* When a list of tools is supplied, the chat template automatically formats this list as a system prompt. See [Chat Template Design](/granite/docs/use-cases/prompt-engineering#chat-template-design) for more information about system prompt design in tool-calling scenarios.
* Please follow OpenAI's function [definition schema](https://platform.openai.com/docs/guides/function-calling?api-mode=responses#defining-functions) to define tools.
* Granite 4.0 chat template automatically returns tool calls between `` and `` tags within the assistant turn. Refer to [Chat Template Design](/granite/docs/use-cases/prompt-engineering#chat-template-design) for examples.
* The Granite 4.0 chat template converts content from `tool` role into a user role, where tool responses appear between `` and `` tags. This conversion occurs automatically when using libraries that apply the chat template for you. However, users who build prompts directly in `Jinja` must ensure that tool responses are formatted according to the Granite 4.0 chat template. Please refer to [Chat Template Design](/granite/docs/use-cases/prompt-engineering#chat-template-design) for examples.
### RAG
```python Transformers theme={null}
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
device = "cuda"
model_path = "ibm-granite/granite-4.0-h-tiny"
tokenizer = AutoTokenizer.from_pretrained(model_path)
# drop device_map if running on CPU
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
model.eval()
chat=[
{"role": "user", "content": "Could you please tell me what the first Bridget Jones's movie is about?, please be brief in your response."}
]
documents=[
{
"doc_id": 1,
"title": "Bridget Jones: The Edge of Reason (2004)",
"text": "Bridget Jones: The Edge of Reason (2004) - Bridget is currently living a happy life with her lawyer boyfriend Mark Darcy, however not only does she start to become threatened and jealous of Mark's new young intern, she is angered by the fact Mark is a Conservative voter. With so many issues already at hand, things get worse for Bridget as her ex-lover, Daniel Cleaver, re-enters her life; the only help she has are her friends and her reliable diary.",
"source": ""
},
{
"doc_id": 2,
"title": "Bridget Jones's Baby (2016)",
"text": "Bridget Jones's Baby (2016) - Bridget Jones is struggling with her current state of life, including her break up with her love Mark Darcy. As she pushes forward and works hard to find fulfillment in her life seems to do wonders until she meets a dashing and handsome American named Jack Quant. Things from then on go great, until she discovers that she is pregnant but the biggest twist of all, she does not know if Mark or Jack is the father of her child.",
"source": ""
},
{
"doc_id": 3,
"title": "Bridget Jones's Diary (2001)",
"text": "Bridget Jones's Diary (2001) - Bridget Jones is a binge drinking and chain smoking thirty-something British woman trying to keep her love life in order while also dealing with her job as a publisher. When she attends a Christmas party with her parents, they try to set her up with their neighbours' son, Mark. After being snubbed by Mark, she starts to fall for her boss Daniel, a handsome man who begins to send her suggestive e-mails that leads to a dinner date. Daniel reveals that he and Mark attended college together, in that time Mark had an affair with his fiancée. Bridget decides to get a new job as a TV presenter after finding Daniel being frisky with a colleague. At a dinner party, she runs into Mark who expresses his affection for her, Daniel claims he wants Bridget back, the two fight over her and Bridget must make a decision who she wants to be with.",
"source": ""
},
]
chat = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True, documents=documents)
# tokenize the text
input_tokens = tokenizer(chat, return_tensors="pt").to(device)
# generate output tokens
output = model.generate(**input_tokens,
max_new_tokens=800, temperature=0)
# decode output tokens into text
output = tokenizer.batch_decode(output)
# print output
print(output[0])
```
```python watsonx.ai theme={null}
### This snippet assumes watsonx.ai access.
### If not already setup, follow the guide here:
### https://github.com/ibm-granite-community/granite-kitchen/blob/main/recipes/Getting_Started/Getting_Started_with_WatsonX.ipynb
import requests
import json
WATSONX_APIKEY = "WATSONX_APIKEY" # Replace with your watsonx.ai API key
WATSONX_PROJECT_ID = "WATSONX_PROJECT_ID" # Replace with your watsonx.ai project id
# STEP 1: Retrieve bearer token using WATSONX_APIKEY
token_url = "https://iam.cloud.ibm.com/oidc/token"
token_data = {
"grant_type": "urn:ibm:params:oauth:grant-type:apikey",
"apikey": WATSONX_APIKEY,
}
token_headers = {"Content-Type": "application/x-www-form-urlencoded"}
token_response = requests.post(token_url, data=token_data, headers=token_headers)
if token_response.status_code != 200:
raise Exception("Failed to retrieve token: " + token_response.text)
access_token = token_response.json()["access_token"]
# STEP 2: Setup call to the chat endpoint in watsonx.ai
url = "https://us-south.ml.cloud.ibm.com/ml/v1/text/chat?version=2025-10-25"
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": f"Bearer {access_token}",
}
chat = [
{
"role": "user",
"content": "Could you please tell me what the first Bridget Jones's movie is about?, please be brief in your response.",
}
]
documents = [
{
"doc_id": "1",
"title": "Bridget Jones: The Edge of Reason (2004)",
"text": "Bridget Jones: The Edge of Reason (2004) - Bridget is currently living a happy life with her lawyer boyfriend Mark Darcy, however not only does she start to become threatened and jealous of Mark's new young intern, she is angered by the fact Mark is a Conservative voter. With so many issues already at hand, things get worse for Bridget as her ex-lover, Daniel Cleaver, re-enters her life; the only help she has are her friends and her reliable diary.",
"source": "",
},
{
"doc_id": "2",
"title": "Bridget Jones's Baby (2016)",
"text": "Bridget Jones's Baby (2016) - Bridget Jones is struggling with her current state of life, including her break up with her love Mark Darcy. As she pushes forward and works hard to find fulfillment in her life seems to do wonders until she meets a dashing and handsome American named Jack Quant. Things from then on go great, until she discovers that she is pregnant but the biggest twist of all, she does not know if Mark or Jack is the father of her child.",
"source": "",
},
{
"doc_id": "3",
"title": "Bridget Jones's Diary (2001)",
"text": "Bridget Jones's Diary (2001) - Bridget Jones is a binge drinking and chain smoking thirty-something British woman trying to keep her love life in order while also dealing with her job as a publisher. When she attends a Christmas party with her parents, they try to set her up with their neighbours' son, Mark. After being snubbed by Mark, she starts to fall for her boss Daniel, a handsome man who begins to send her suggestive e-mails that leads to a dinner date. Daniel reveals that he and Mark attended college together, in that time Mark had an affair with his fiancée. Bridget decides to get a new job as a TV presenter after finding Daniel being frisky with a colleague. At a dinner party, she runs into Mark who expresses his affection for her, Daniel claims he wants Bridget back, the two fight over her and Bridget must make a decision who she wants to be with.",
"source": "",
},
]
body = {
"messages": chat,
"chat_template_kwargs": {"documents": documents},
"project_id": WATSONX_PROJECT_ID,
"model_id": "ibm/granite-4-h-small",
"max_completion_tokens": 2000,
"temperature": 0,
}
# STEP 3: Execute call to the chat endpoint in watsonx.ai
response = requests.post(url, headers=headers, json=body)
if response.status_code != 200:
raise Exception("Non-200 response: " + str(response.text))
data = response.json()
print(json.dumps(data, indent=4))
```
```python OpenAI API theme={null}
### This snippet assumes access to an OpenAI compatible endpoint
### If not already setup, an example setup can be achieved
### through vLLM. Follow the guide here:
### https://www.ibm.com/granite/docs/run/granite-with-vllm-containerized
import requests
import json
# STEP 1: Setup call to the OpenAI compatible endpoint
url = "/chat/completions"
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
}
chat = [
{
"role": "user",
"content": "Could you please tell me what the first Bridget Jones's movie is about?, please be brief in your response.",
}
]
documents = [
{
"doc_id": "1",
"title": "Bridget Jones: The Edge of Reason (2004)",
"text": "Bridget Jones: The Edge of Reason (2004) - Bridget is currently living a happy life with her lawyer boyfriend Mark Darcy, however not only does she start to become threatened and jealous of Mark's new young intern, she is angered by the fact Mark is a Conservative voter. With so many issues already at hand, things get worse for Bridget as her ex-lover, Daniel Cleaver, re-enters her life; the only help she has are her friends and her reliable diary.",
"source": "",
},
{
"doc_id": "2",
"title": "Bridget Jones's Baby (2016)",
"text": "Bridget Jones's Baby (2016) - Bridget Jones is struggling with her current state of life, including her break up with her love Mark Darcy. As she pushes forward and works hard to find fulfillment in her life seems to do wonders until she meets a dashing and handsome American named Jack Quant. Things from then on go great, until she discovers that she is pregnant but the biggest twist of all, she does not know if Mark or Jack is the father of her child.",
"source": "",
},
{
"doc_id": "3",
"title": "Bridget Jones's Diary (2001)",
"text": "Bridget Jones's Diary (2001) - Bridget Jones is a binge drinking and chain smoking thirty-something British woman trying to keep her love life in order while also dealing with her job as a publisher. When she attends a Christmas party with her parents, they try to set her up with their neighbours' son, Mark. After being snubbed by Mark, she starts to fall for her boss Daniel, a handsome man who begins to send her suggestive e-mails that leads to a dinner date. Daniel reveals that he and Mark attended college together, in that time Mark had an affair with his fiancée. Bridget decides to get a new job as a TV presenter after finding Daniel being frisky with a colleague. At a dinner party, she runs into Mark who expresses his affection for her, Daniel claims he wants Bridget back, the two fight over her and Bridget must make a decision who she wants to be with.",
"source": "",
},
]
body = {
"messages": chat,
"chat_template_kwargs": {"documents": documents},
"model_id": "ibm-granite/granite-4.0-h-small",
"max_completion_tokens": 2000,
"temperature": 0,
}
# note: chat_template_kwargs is an additional parameter
# exposed by libraries such as vLLM and not part of the
# original OpenAI Chat Completions parameter specification.
# STEP 2: Execute call to the chat endpoint
response = requests.post(url, headers=headers, json=body)
if response.status_code != 200:
raise Exception("Non-200 response: " + str(response.text))
data = response.json()
print(json.dumps(data, indent=4))
```
```text Chat Template theme={null}
<|start_of_role|>system<|end_of_role|>You are a helpful assistant with access to the following documents. You may use one or more documents to assist with the user query.
You are given a list of documents within XML tags:
{"doc_id": 1, "title": "Bridget Jones: The Edge of Reason (2004)", "text": "Bridget Jones: The Edge of Reason (2004) - Bridget is currently living a happy life with her lawyer boyfriend Mark Darcy, however not only does she start to become threatened and jealous of Mark's new young intern, she is angered by the fact Mark is a Conservative voter. With so many issues already at hand, things get worse for Bridget as her ex-lover, Daniel Cleaver, re-enters her life; the only help she has are her friends and her reliable diary.", "source": ""}
{"doc_id": 2, "title": "Bridget Jones's Baby (2016)", "text": "Bridget Jones's Baby (2016) - Bridget Jones is struggling with her current state of life, including her break up with her love Mark Darcy. As she pushes forward and works hard to find fulfillment in her life seems to do wonders until she meets a dashing and handsome American named Jack Quant. Things from then on go great, until she discovers that she is pregnant but the biggest twist of all, she does not know if Mark or Jack is the father of her child.", "source": ""}
{"doc_id": 3, "title": "Bridget Jones's Diary (2001)", "text": "Bridget Jones's Diary (2001) - Bridget Jones is a binge drinking and chain smoking thirty-something British woman trying to keep her love life in order while also dealing with her job as a publisher. When she attends a Christmas party with her parents, they try to set her up with their neighbours' son, Mark. After being snubbed by Mark, she starts to fall for her boss Daniel, a handsome man who begins to send her suggestive e-mails that leads to a dinner date. Daniel reveals that he and Mark attended college together, in that time Mark had an affair with his fiancée. Bridget decides to get a new job as a TV presenter after finding Daniel being frisky with a colleague. At a dinner party, she runs into Mark who expresses his affection for her, Daniel claims he wants Bridget back, the two fight over her and Bridget must make a decision who she wants to be with.", "source": ""}
Write the response to the user's input by strictly aligning with the facts in the provided documents. If the information needed to answer the question is not available in the documents, inform the user that the question cannot be answered based on the available data.<|end_of_text|>
<|start_of_role|>user<|end_of_role|>Could you please tell me what the first Bridget Jones's movie is about?, please be brief in your response.<|end_of_text|>
<|start_of_role|>assistant<|end_of_role|>The first Bridget Jones's movie, "Bridget Jones's Diary" (2001), is about a thirty-something British woman named Bridget Jones who is trying to keep her love life in order while also dealing with her job as a publisher. She attends a Christmas party with her parents, where they try to set her up with their neighbours' son, Mark. After being snubbed by Mark, she starts to fall for her boss Daniel, a handsome man who begins to send her suggestive emails. Bridget decides to get a new job as a TV presenter after finding Daniel being frisky with a colleague. At a dinner party, she runs into Mark who expresses his affection for her, Daniel claims he wants Bridget back, the two fight over her and Bridget must make a decision who she wants to be with.<|end_of_text|>
```
Consider the following points to build prompts for RAG tasks:
* The chat template lists documents as part of the `system` turn between `` and `` tags. Please refer to [Chat Template Design](/granite/docs/use-cases/prompt-engineering#chat-template-design) for further details.
* Documents are provided to the model as a list of dictionaries, with each dictionary representing a document. We recommend formatting documents as follows:
```
{
"doc_id": 1,
"title": "History Document Title",
"text": "From the early 12th century, French builders developed the Gothic style, marked by the use of rib vaults, pointed arches, flying buttresses, and large stained glass windows. It was used mainly in churches and cathedrals, and continued in use until the 16th century in much of Europe. Classic examples of Gothic architecture include Chartres Cathedral and Reims Cathedral in France as well as Salisbury Cathedral in England. Stained glass became a crucial element in the design of churches, which continued to use extensive wall-paintings, now almost all lost.",
"source": ""
}
```
### FIM
```python Transformers theme={null}
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
device = "cuda"
model_path = "ibm-granite/granite-4.0-micro"
tokenizer = AutoTokenizer.from_pretrained(model_path)
# drop device_map if running on CPU
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
model.eval()
prompt = """<|fim_prefix|>
def fibonacci(n):
result =
<|fim_suffix|>
return result
<|fim_middle|>"""
chat = [
{ "role": "user", "content": prompt},
]
chat = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
# tokenize the text
input_tokens = tokenizer(chat, return_tensors="pt").to(device)
# generate output tokens
output = model.generate(**input_tokens,
max_new_tokens=50, temperature=0)
# decode output tokens into text
output = tokenizer.batch_decode(output)
# print output
print(output[0])
```
```python watsonx.ai theme={null}
### This snippet assumes watsonx.ai access.
### If not already setup, follow the guide here:
### https://github.com/ibm-granite-community/granite-kitchen/blob/main/recipes/Getting_Started/Getting_Started_with_WatsonX.ipynb
import requests
import json
WATSONX_APIKEY = "WATSONX_APIKEY" # Replace with your watsonx.ai API key
WATSONX_PROJECT_ID = "WATSONX_PROJECT_ID" # Replace with your watsonx.ai project id
# STEP 1: Retrieve bearer token using WATSONX_APIKEY
token_url = "https://iam.cloud.ibm.com/oidc/token"
token_data = {
"grant_type": "urn:ibm:params:oauth:grant-type:apikey",
"apikey": WATSONX_APIKEY,
}
token_headers = {"Content-Type": "application/x-www-form-urlencoded"}
token_response = requests.post(token_url, data=token_data, headers=token_headers)
if token_response.status_code != 200:
raise Exception("Failed to retrieve token: " + token_response.text)
access_token = token_response.json()["access_token"]
# STEP 2: Setup call to the chat endpoint in watsonx.ai
url = "https://us-south.ml.cloud.ibm.com/ml/v1/text/chat?version=2025-10-25"
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": f"Bearer {access_token}",
}
prompt = """<|fim_prefix|>
def fibonacci(n):
result =
<|fim_suffix|>
return result
<|fim_middle|>"""
chat = [
{"role": "user", "content": prompt},
]
body = {
"messages": chat,
"project_id": WATSONX_PROJECT_ID,
"model_id": "ibm/granite-4-h-small",
"max_completion_tokens": 2000,
"temperature": 0,
}
# STEP 3: Execute call to the chat endpoint in watsonx.ai
response = requests.post(url, headers=headers, json=body)
if response.status_code != 200:
raise Exception("Non-200 response: " + str(response.text))
data = response.json()
print(json.dumps(data, indent=4))
```
```python OpenAI API theme={null}
### This snippet assumes access to an OpenAI compatible endpoint
### If not already setup, an example setup can be achieved
### through vLLM. Follow the guide here:
### https://www.ibm.com/granite/docs/run/granite-with-vllm-containerized
import requests
import json
# STEP 1: Setup call to the OpenAI compatible endpoint
url = "/chat/completions"
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
}
prompt = """<|fim_prefix|>
def fibonacci(n):
result =
<|fim_suffix|>
return result
<|fim_middle|>"""
chat = [
{"role": "user", "content": prompt},
]
body = {
"messages": chat,
"model_id": "ibm-granite/granite-4.0-h-small",
"max_completion_tokens": 2000,
"temperature": 0,
}
# STEP 2: Execute call to the chat endpoint
response = requests.post(url, headers=headers, json=body)
if response.status_code != 200:
raise Exception("Non-200 response: " + str(response.text))
data = response.json()
print(json.dumps(data, indent=4))
```
```text Chat Template theme={null}
<|start_of_role|>user<|end_of_role|><|fim_prefix|>
def fibonacci(n):
result =
<|fim_suffix|>
return result
<|fim_middle|><|end_of_text|>
<|start_of_role|>assistant<|end_of_role|> if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
<|end_of_text|>
```
Consider the following points to build prompts for FIM coding tasks:
* The tags supported for fill-in-the-middle (FIM) code completion are: `<|fim_prefix|>`, `<|fim_middle|>`, and `<|fim_suffix|>`. Make sure to use the correct FIM tags when using Granite 4.0 models for FIM code completions.
* Prepend code before the missing part with the tag `<|fim_prefix|>`
* Prepend code after the missing part with the tag `<|fim_suffix|>`
* End your prompt with the tag `<|fim_middle|>` to indicate to the model something is missing in the code snippet.
* Completion of basic programming concepts (e.g., function, method, conditionals, loops) is covered for various programming languages (e.g., python, c/c++, go, java).
### JSON output
```python Transformers theme={null}
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
device = "cuda"
model_path = "ibm-granite/granite-4.0-h-tiny"
tokenizer = AutoTokenizer.from_pretrained(model_path)
# drop device_map if running on CPU
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
model.eval()
chat = [
{
"role": "system",
"content": "You are a helpful assistant that answers in JSON. Here's the json schema you must adhere to:\n\n{\"title\": \"LeisureActivityBooking\", \"type\": \"object\", \"properties\": {\"activityID\": {\"title\": \"Activity ID\", \"type\": \"string\"}, \"participantInfo\": {\"title\": \"Participant Info\", \"type\": \"object\", \"properties\": {\"participantName\": {\"title\": \"Participant Name\", \"type\": \"string\"}, \"age\": {\"title\": \"Age\", \"type\": \"integer\"}}, \"required\": [\"participantName\", \"age\"]}, \"activityDate\": {\"title\": \"Activity Date\", \"type\": \"string\", \"format\": \"date\"}, \"equipmentNeeded\": {\"title\": \"Equipment Needed\", \"type\": \"array\", \"items\": {\"type\": \"string\"}}}, \"required\": [\"activityID\", \"participantInfo\", \"activityDate\"]}\n\n"
},
{
"role": "user",
"content": "I'm planning a kayaking trip for my friend's birthday on April 15th, and I need to book it through your leisure activity service. The activity will be for my friend, Jamie Patterson, who is 27 years old. We'll need two kayaks, paddles, and safety vests. The activity ID for this booking is 'KAYAK-0423'. The date we're looking to book the kayaking activity is specifically on the 15th of April, 2023. To summarize, the equipment needed for this adventure includes two kayaks, a pair of paddles, and two safety vests to ensure a safe and enjoyable experience on the water."
}
]
chat = tokenizer.apply_chat_template(chat,tokenize=False, add_generation_prompt=True)
# tokenize the text
input_tokens = tokenizer(chat, return_tensors="pt").to(device)
# generate output tokens
output = model.generate(**input_tokens,
max_new_tokens=200, temperature=0)
# decode output tokens into text
output = tokenizer.batch_decode(output)
# print output
print(output[0])
```
```python watsonx.ai theme={null}
### This snippet assumes watsonx.ai access.
### If not already setup, follow the guide here:
### https://github.com/ibm-granite-community/granite-kitchen/blob/main/recipes/Getting_Started/Getting_Started_with_WatsonX.ipynb
import requests
import json
WATSONX_APIKEY = "WATSONX_APIKEY" # Replace with your watsonx.ai API key
WATSONX_PROJECT_ID = "WATSONX_PROJECT_ID" # Replace with your watsonx.ai project id
# STEP 1: Retrieve bearer token using WATSONX_APIKEY
token_url = "https://iam.cloud.ibm.com/oidc/token"
token_data = {
"grant_type": "urn:ibm:params:oauth:grant-type:apikey",
"apikey": WATSONX_APIKEY,
}
token_headers = {"Content-Type": "application/x-www-form-urlencoded"}
token_response = requests.post(token_url, data=token_data, headers=token_headers)
if token_response.status_code != 200:
raise Exception("Failed to retrieve token: " + token_response.text)
access_token = token_response.json()["access_token"]
# STEP 2: Setup call to the chat endpoint in watsonx.ai
url = "https://us-south.ml.cloud.ibm.com/ml/v1/text/chat?version=2025-10-25"
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": f"Bearer {access_token}",
}
chat = [
{
"role": "system",
"content": 'You are a helpful assistant that answers in JSON. Here\'s the json schema you must adhere to:\n\n{"title": "LeisureActivityBooking", "type": "object", "properties": {"activityID": {"title": "Activity ID", "type": "string"}, "participantInfo": {"title": "Participant Info", "type": "object", "properties": {"participantName": {"title": "Participant Name", "type": "string"}, "age": {"title": "Age", "type": "integer"}}, "required": ["participantName", "age"]}, "activityDate": {"title": "Activity Date", "type": "string", "format": "date"}, "equipmentNeeded": {"title": "Equipment Needed", "type": "array", "items": {"type": "string"}}}, "required": ["activityID", "participantInfo", "activityDate"]}\n\n',
},
{
"role": "user",
"content": "I'm planning a kayaking trip for my friend's birthday on April 15th, and I need to book it through your leisure activity service. The activity will be for my friend, Jamie Patterson, who is 27 years old. We'll need two kayaks, paddles, and safety vests. The activity ID for this booking is 'KAYAK-0423'. The date we're looking to book the kayaking activity is specifically on the 15th of April, 2023. To summarize, the equipment needed for this adventure includes two kayaks, a pair of paddles, and two safety vests to ensure a safe and enjoyable experience on the water.",
},
]
body = {
"messages": chat,
"project_id": WATSONX_PROJECT_ID,
"model_id": "ibm/granite-4-h-small",
"max_completion_tokens": 2000,
"temperature": 0,
}
# STEP 3: Execute call to the chat endpoint in watsonx.ai
response = requests.post(url, headers=headers, json=body)
if response.status_code != 200:
raise Exception("Non-200 response: " + str(response.text))
data = response.json()
print(json.dumps(data, indent=4))
```
```python OpenAI API theme={null}
### This snippet assumes access to an OpenAI compatible endpoint
### If not already setup, an example setup can be achieved
### through vLLM. Follow the guide here:
### https://www.ibm.com/granite/docs/run/granite-with-vllm-containerized
import requests
import json
# STEP 1: Setup call to the OpenAI compatible endpoint
url = "/chat/completions"
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
}
chat = [
{
"role": "system",
"content": 'You are a helpful assistant that answers in JSON. Here\'s the json schema you must adhere to:\n\n{"title": "LeisureActivityBooking", "type": "object", "properties": {"activityID": {"title": "Activity ID", "type": "string"}, "participantInfo": {"title": "Participant Info", "type": "object", "properties": {"participantName": {"title": "Participant Name", "type": "string"}, "age": {"title": "Age", "type": "integer"}}, "required": ["participantName", "age"]}, "activityDate": {"title": "Activity Date", "type": "string", "format": "date"}, "equipmentNeeded": {"title": "Equipment Needed", "type": "array", "items": {"type": "string"}}}, "required": ["activityID", "participantInfo", "activityDate"]}\n\n',
},
{
"role": "user",
"content": "I'm planning a kayaking trip for my friend's birthday on April 15th, and I need to book it through your leisure activity service. The activity will be for my friend, Jamie Patterson, who is 27 years old. We'll need two kayaks, paddles, and safety vests. The activity ID for this booking is 'KAYAK-0423'. The date we're looking to book the kayaking activity is specifically on the 15th of April, 2023. To summarize, the equipment needed for this adventure includes two kayaks, a pair of paddles, and two safety vests to ensure a safe and enjoyable experience on the water.",
},
]
body = {
"messages": chat,
"model_id": "ibm-granite/granite-4.0-h-small",
"max_completion_tokens": 2000,
"temperature": 0,
"response_format": {"type": "json_object"},
}
# STEP 2: Execute call to the chat endpoint
response = requests.post(url, headers=headers, json=body)
if response.status_code != 200:
raise Exception("Non-200 response: " + str(response.text))
data = response.json()
print(json.dumps(data, indent=4))
```
```text Chat Template theme={null}
<|start_of_role|>system<|end_of_role|>You are a helpful assistant that answers in JSON. Here's the json schema you must adhere to:
{"title": "LeisureActivityBooking", "type": "object", "properties": {"activityID": {"title": "Activity ID", "type": "string"}, "participantInfo": {"title": "Participant Info", "type": "object", "properties": {"participantName": {"title": "Participant Name", "type": "string"}, "age": {"title": "Age", "type": "integer"}}, "required": ["participantName", "age"]}, "activityDate": {"title": "Activity Date", "type": "string", "format": "date"}, "equipmentNeeded": {"title": "Equipment Needed", "type": "array", "items": {"type": "string"}}}, "required": ["activityID", "participantInfo", "activityDate"]}
<|end_of_text|>
<|start_of_role|>user<|end_of_role|>I'm planning a kayaking trip for my friend's birthday on April 15th, and I need to book it through your leisure activity service. The activity will be for my friend, Jamie Patterson, who is 27 years old. We'll need two kayaks, paddles, and safety vests. The activity ID for this booking is 'KAYAK-0423'. The date we're looking to book the kayaking activity is specifically on the 15th of April, 2023. To summarize, the equipment needed for this adventure includes two kayaks, a pair of paddles, and two safety vests to ensure a safe and enjoyable experience on the water.<|end_of_text|>
<|start_of_role|>assistant<|end_of_role|>{"activityID": "KAYAK-0423", "participantInfo": {"participantName": "Jamie Patterson", "age": 27}, "activityDate": "2023-04-15", "equipmentNeeded": ["kayak", "paddle", "safety vest"]}<|end_of_text|>
```
## Backward Compatibility
Prompt templates designed for basic inference tasks should remain compatible with Granite 4.0 models. However, more complex templates may require a migration process. To take full advantage of Granite 4.0 models, please refer to this prompt engineering guide to create new templates or migrating existing ones.
Some points to consider while migrating templates are:
* The chat template in this version handles lists of tools and documents differently. This update is applied automatically when using the `apply_chat_template` function from the transformers library to construct prompts. However, users who craft `Jinja` templates manually must ensure they follow the updated chat template format. Please refer to [Chat Template Design](/granite/docs/use-cases/prompt-engineering#chat-template-design) for more details.
* Controls for `length` and `originality` have been deprecated, they are no longer supported in this version.
# Granite 4.1
Source: https://wwwpoc.ibm.com/granite/docs/models/granite4-1
View the full Granite 4.1 collection on Hugging Face
Granite 4.1 models and documentation
## Overview
**Granite 4.1** is a family of dense language models available in three sizes: 3B, 8B, and 30B parameters. Each size is available in both base and instruction-tuned variants, with optional FP8 quantization for efficient deployment. Built with a dense architecture, Granite 4.1 demonstrates significant improvements over Granite 4.0 in tool calling, instruction following, coding capabilities, and mathematical reasoning.
### Model Variants
* **granite-4.1-3b-base** & **granite-4.1-3b-instruct**: Compact model optimized for edge deployment and resource-constrained environments
* **granite-4.1-8b-base** & **granite-4.1-8b-instruct**: Balanced model for general-purpose enterprise applications
* **granite-4.1-30b-base** & **granite-4.1-30b-instruct**: High-capacity model for complex reasoning and specialized tasks
All models are released under the Apache 2.0 license with cryptographic signatures, ISO certification, and full transparency disclosures.
### Key Capabilities
**Tool Calling**: Granite 4.1 demonstrates strong ability to understand and execute tool-based instructions, enabling seamless integration with various software tools and APIs. This capability allows enterprises to create powerful AI-driven workflows and automate complex tasks.
**Instruction Following**: Granite 4.1 exhibits improved comprehension and adherence to user instructions, ensuring reliable and accurate task completion for enterprise automation.
**Code Generation & Explanation**: Granite 4.1 generates code snippets and explains complex codebases across multiple programming languages with higher accuracy, accelerating software development workflows.
**Mathematical Reasoning**: Granite 4.1 tackles complex mathematical problems from basic arithmetic to advanced calculus and linear algebra, enabling automated calculation and decision-making.
## Getting Started
First, install the required libraries:
```bash Install theme={null}
pip install torch torchvision torchaudio
pip install accelerate
pip install transformers
```
### Generation
This is a simple example of how to use Granite-4.1-30B model:
```python Python theme={null}
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
device = "cuda"
model_path = "ibm-granite/granite-4.1-30b"
tokenizer = AutoTokenizer.from_pretrained(model_path)
# drop device_map if running on CPU
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
model.eval()
# change input text as desired
chat = [
{ "role": "user", "content": "Please list one IBM Research laboratory located in the United States. You should only output its name and location." },
]
chat = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
# tokenize the text
input_tokens = tokenizer(chat, return_tensors="pt").to(device)
# generate output tokens
output = model.generate(**input_tokens,
max_new_tokens=100)
# decode output tokens into text
output = tokenizer.batch_decode(output)
# print output
print(output[0])
```
Expected output:
```text Output theme={null}
<|start_of_role|>user<|end_of_role|>Please list one IBM Research laboratory located in the United States. You should only output its name and location.<|end_of_text|>
<|start_of_role|>assistant<|end_of_role|>IBM Research - Almaden, San Jose, California<|end_of_text|>
```
### Tool Calling
Granite-4.1-30B comes with enhanced tool calling capabilities, enabling seamless integration with external functions and APIs. Define a list of tools using OpenAI's function definition schema:
```python Python theme={null}
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
device = "cuda"
model_path = "ibm-granite/granite-4.1-30b"
tokenizer = AutoTokenizer.from_pretrained(model_path)
# drop device_map if running on CPU
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
model.eval()
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather for a specified city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "Name of the city"
}
},
"required": ["city"]
}
}
}
]
# change input text as desired
chat = [
{ "role": "user", "content": "What's the weather like in Boston right now?" },
]
chat = tokenizer.apply_chat_template(chat, \
tokenize=False, \
tools=tools, \
add_generation_prompt=True)
# tokenize the text
input_tokens = tokenizer(chat, return_tensors="pt").to(device)
# generate output tokens
output = model.generate(**input_tokens,
max_new_tokens=100)
# decode output tokens into text
output = tokenizer.batch_decode(output)
# print output
print(output[0])
```
Expected output:
```text Output theme={null}
<|start_of_role|>system<|end_of_role|>You are a helpful assistant with access to the following tools. You may call one or more tools to assist with the user query.
You are provided with function signatures within XML tags:
{"type": "function", "function": {"name": "get_current_weather", "description": "Get the current weather for a specified city.", "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "Name of the city"}}, "required": ["city"]}}}
For each tool call, return a json object with function name and arguments within XML tags:
{"name": , "arguments": }
. If a tool does not exist in the provided list of tools, notify the user that you do not have the ability to fulfill the request.<|end_of_text|>
<|start_of_role|>user<|end_of_role|>What's the weather like in Boston right now?<|end_of_text|>
<|start_of_role|>assistant<|end_of_role|>
{"name": "get_current_weather", "arguments": {"city": "Boston"}}
<|end_of_text|>
```
# Granite Guardian 4.1
Source: https://wwwpoc.ibm.com/granite/docs/models/guardian
View the full Granite Guardian collection on Hugging Face
Download and run Granite Guardian with Ollama
Check out Granite Guardian in action
Try out the quick start guide to identify potential risks
Visit the GitHub repository for all Granite Guardian resources
## What's New
**Granite Guardian 4.1 8B** introduces improved **Bring Your Own Criteria (BYOC)** support, enabling users to define arbitrary judging criteria beyond the pre-baked safety and hallucination detectors. The model can now faithfully evaluate complex, multi-part requirements such as formatting rules, length constraints, and domain-specific instructions.
Key improvements over Granite Guardian 3.3:
* **BYOC capability**: Significant gains on instruction-following and requirement checking benchmarks, enabling the model to faithfully judge complex, multi-part user-defined criteria.
* **Best-of-N reward model**: Can serve as a reward model for best-of-N selection on verifiable tasks, outperforming dedicated reward models up to 70B parameters.
* **Hybrid thinking**: Supports both thinking mode (with detailed reasoning traces) and non-thinking mode (low-latency yes/no judgements).
* **Function calling**: Stronger hallucination detection in agentic workflows.
* **Maintained safety and groundedness**: Maintains strong performance on OOD safety and RAG groundedness benchmarks.
## Overview
The **Granite Guardian** models are a family of models and LoRA adapters designed to judge if its input and output meet specified criteria. The model comes pre-baked with certain criteria, but is not limited to: jailbreak attempts, profanity, and hallucinations related to tool calls and RAG (retrieval augmented generation) in agent-based systems. Additionally, the model enables users to bring their own criteria (BYOC) and tailor its judging behavior for their specified use case(s). The Granite Guardian LoRA adapters can be layered atop the Granite Guardian models to tackle more specific, downstream tasks.
This version of Granite Guardian is a hybrid thinking model that allows the user to operate in thinking or non-thinking mode. In the thinking mode, the model produces detailed reasoning traces with `` and `` tags. In the non-thinking mode, the model only produces the judgement score through `` tags. Since its inception, Granite Guardian has remained in the top 3 on the [LLM-Aggrefact Leaderboard](https://llm-aggrefact.github.io/) (as of 10/2/2025).
The Granite Guardian models are enterprise-grade, risk detection models that are applicable across a wide-range of enterprise applications:
* Detecting harm-related risks within prompt text, model responses, or conversations (as guardrails). These present fundamentally different use cases as the first assesses user supplied text, the second evaluates model generated text, and the third evaluates the last turn of a conversation.
* RAG (retrieval-augmented generation) use-case where the guardian model assesses three key issues: context relevance (whether the retrieved context is relevant to the query), groundedness (whether the response is accurate and faithful to the provided context), and answer relevance (whether the response directly addresses the user's query).
* Function calling risk detection within agentic workflows, where Granite Guardian evaluates intermediate steps for syntactic and semantic hallucinations. This includes assessing the validity of function calls and detecting fabricated information, particularly during query translation.
* **Bring Your Own Criteria (BYOC)**: Users can define arbitrary evaluation rules to judge whether LLM outputs satisfy diverse requirements such as formatting rules, length constraints, or domain-specific instructions.
These are enterprise-grade models trained in a transparent manner, and according to IBM's AI Ethics principles. They are released under the Apache 2.0 license for research and commercial use.
[Granite Guardian Paper](https://arxiv.org/abs/2412.07724)
### Prompting Guide
Granite Guardian 4.1 uses a structured prompt format to instruct the model to judge text against a given criterion.
#### 1. Think / No-Think Instruction
Every guardian block begins with a mode selector that controls whether the model produces reasoning traces before scoring:
* **Think mode** (``): The model reasons step-by-step inside `...` tags before emitting a score. Use this when you want interpretable justifications.
* **No-think mode** (``): The model skips reasoning and outputs the score directly. Use this for lower-latency evaluation where only the yes/no judgement is needed.
The two instruction strings are:
```
# Think mode
As a judge agent, carefully analyze whether the provided text meets the
given judging criteria. Use all available information, including conversations,
documents, and tools. Reason through the evidence step by step before providing
your score. Wrap your reasoning in tags, then provide your
score in tags.
# No-think mode
As a judge agent, assess whether the provided text meets the given
judging criteria using all available information, including conversations,
documents, and tools. Provide your score immediately without explanation.
Output empty \n tags followed by your score in tags.
```
#### 2. Criteria
After the mode instruction, the block includes a `### Criteria:` section that tells the model *what* to judge. This can be:
* A **pre-baked criterion**, one of the built-in definitions (e.g., function calling hallucination, groundedness, jailbreaking). See the full list below.
* A **custom (BYOC) criterion**, any user-defined rule expressed in natural language (e.g., *"The response contains no more than 3 sentences."*).
#### 3. Scoring Schema
The block always ends with:
```
### Scoring Schema: If the last assistant's text meets the criteria, return 'yes'; otherwise, return 'no'.
```
#### Putting It Together
The complete guardian block is appended as the final user message:
```
{think_or_nothink_instruction}
### Criteria: {criteria_text}
### Scoring Schema: If the last assistant's text meets the criteria, return 'yes'; otherwise, return 'no'.
```
After applying the chat template, a **think prefix** is appended to the generation prompt:
* Think mode: `\n`
* No-think mode: `\n\n`
### Definitions for Pre-Baked Criteria
The model is specifically trained to judge if text meets any of the following criteria:
* **Harm**: content considered generally harmful.
* **Social Bias**: prejudice based on identity or characteristics.
* **Jailbreaking**: deliberate instances of manipulating AI to generate harmful, undesired, or inappropriate content.
* **Violence**: content promoting physical, mental, or sexual harm.
* **Profanity**: use of offensive language or insults.
* **Sexual Content**: explicit or suggestive material of a sexual nature.
* **Unethical Behavior**: actions that violate moral or legal standards.
The model also assesses hallucination risks in RAG pipelines:
* **Context Relevance**: retrieved context is not pertinent to answering the user's question or addressing their needs.
* **Groundedness**: assistant's response includes claims or facts not supported by or contradicted by the provided context.
* **Answer Relevance**: assistant's response fails to address or properly respond to the user's input.
The model is moreover equipped to detect risks in agentic workflows:
* **Function Calling Hallucination**: assistant's response contains function calls that have syntax or semantic errors based on the user query and available tool.
The model can also detect adherence to both **coarse- and fine-grained instructions**, such as "The response contains sufficient detail." or "The last word of your response should be the word demand."
### Dataset
Granite Guardian is trained on a combination of human annotated and synthetic data. Samples from [hh-rlhf](https://huggingface.co/datasets/Anthropic/hh-rlhf) dataset were used to obtain responses from Granite and Mixtral models. These prompt-response pairs were annotated for different risk dimensions by a socioeconomically diverse group of people at DataForce. DataForce prioritizes the well-being of its data contributors by ensuring they are paid fairly and receive livable wages for all projects. Additional synthetic data was used to supplement the training set to improve performance for RAG, jailbreak, conversational, and function calling hallucination related risks.
## Use Granite Guardian
[Cookbooks](https://github.com/ibm-granite/granite-guardian/tree/main/cookbooks) offer an excellent starting point for working with the models, providing a variety of examples that demonstrate how they can be configured for scenarios.
* [Quick Start Guide](https://github.com/ibm-granite/granite-guardian/tree/main/cookbooks/granite-guardian-4.1/quickstart.ipynb) provides steps to start using Granite Guardian for judging prompts (user message), responses (assistant message), RAG use cases, or agentic workflows.
* [Detailed Guide](https://github.com/ibm-granite/granite-guardian/tree/main/cookbooks/granite-guardian-4.1/detailed_guide.ipynb) explores different pre-baked criteria in depth and shows how to assess custom criteria with Granite Guardian.
### Quick start example
The model is pre-baked with certain judging criteria (see the section titled Definitions for Pre-baked Criteria for the complete list). We will now see a few examples of how to use the pre-baked criteria as well as how users can specify their own criteria. We will also see how to activate thinking mode.
Let us setup the imports, load the model and a utility function to parse the model outputs including reasoning traces or chain-of-thought.
```python Python theme={null}
import json
import re
from vllm import LLM, SamplingParams
from transformers import AutoTokenizer
model_path = "ibm-granite/granite-guardian-4.1-8b"
# Load tokenizer and model
tokenizer = AutoTokenizer.from_pretrained(model_path)
llm = LLM(model=model_path, max_model_len=8192)
sampling_params = SamplingParams(temperature=0.0, max_tokens=2048)
# Guardian judge instructions for think / no-think modes
GUARDIAN_JUDGE_THINK = (
"As a judge agent, carefully analyze whether the provided text meets the "
"given judging criteria. Use all available information, including conversations, "
"documents, and tools. Reason through the evidence step by step before providing "
"your score. Wrap your reasoning in tags, then provide your "
"score in tags."
)
GUARDIAN_JUDGE_NOTHINK = (
"As a judge agent, assess whether the provided text meets the given "
"judging criteria using all available information, including conversations, "
"documents, and tools. Provide your score immediately without explanation. "
"Output empty \\n tags followed by your score in tags."
)
def build_guardian_block(criteria, think=False):
judge_instruction = GUARDIAN_JUDGE_THINK if think else GUARDIAN_JUDGE_NOTHINK
return (
f"{judge_instruction}\n\n"
f"### Criteria: {criteria}\n\n"
f"### Scoring Schema: If the last assistant's text meets the criteria, "
f"return 'yes'; otherwise, return 'no'."
)
def parse_output(text):
text_clean = re.sub(r".*?", "", text, flags=re.DOTALL).strip()
match = re.findall(r"\s*(.*?)\s*", text_clean, re.DOTALL)
if match:
return match[0].strip().lower()
return None
```
### Example 1: Detect function calling hallucination
```python Python theme={null}
# Define tools, user query, and assistant's function call response
tools = [
{
"name": "comment_list",
"description": "Fetches a list of comments for a specified video using the given API.",
"parameters": {
"aweme_id": {
"description": "The ID of the video.",
"type": "int",
"default": "7178094165614464282"
},
"cursor": {
"description": "The cursor for pagination. Defaults to 0.",
"type": "int, optional",
"default": "0"
},
"count": {
"description": "The number of comments to fetch. Maximum is 30. Defaults to 20.",
"type": "int, optional",
"default": "20"
}
}
}
]
user_text = "Fetch the first 15 comments for the video with ID 456789123."
response_text = json.dumps([{
"name": "comment_list",
"arguments": {
"video_id": 456789123, # Wrong argument name: should be "aweme_id"
"count": 15
}
}])
# Build the guardian prompt (no-think mode)
think = False
criteria = (
"Function call hallucination occurs when a text includes function calls that "
"either don't adhere to the correct format defined by the available tools or "
"are inconsistent with the query's requirements. This risk arises from function "
"calls containing incorrect argument names, values, or types that clash with "
"the tool definitions or the query itself. Common examples include calling "
"functions not present in the tool definitions, providing invalid argument "
"values, or attempting to use parameters that don't exist."
)
messages = [
{"role": "user", "content": user_text},
{"role": "assistant", "content": response_text},
{"role": "user", "content": build_guardian_block(criteria, think=think)},
]
prompt = tokenizer.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True, available_tools=tools
)
# Generate
output = llm.generate([prompt], sampling_params)
response = output[0].outputs[0].text.strip()
score = parse_output(response)
print(f"Hallucination detected: {score}") # yes
```
### Example 2: Detect lack of groundedness in RAG settings (think mode)
```python Python theme={null}
context_text = """Eat (1964) is a 45-minute underground film created by Andy Warhol and featuring painter Robert Indiana, filmed on Sunday, February 2, 1964, in Indiana's studio. The film was first shown by Jonas Mekas on July 16, 1964, at the Washington Square Gallery at 530 West Broadway.
Jonas Mekas (December 24, 1922 – January 23, 2019) was a Lithuanian-American filmmaker, poet, and artist who has been called "the godfather of American avant-garde cinema"."""
documents = [{"doc_id": "0", "text": context_text}]
response_text = "The film Eat was first shown by Jonas Mekas on December 24, 1922 at the Washington Square Gallery at 530 West Broadway."
think = True
criteria = (
"A text is considered ungrounded or unfaithful if it includes information "
"lacking support from, or directly contradicting, the provided document(s). "
"This risk arises when the text fabricates details, misinterprets the content, "
"or makes unsupported extrapolations beyond what is explicitly stated in the "
"document(s)."
)
messages = [
{"role": "assistant", "content": response_text},
{"role": "user", "content": build_guardian_block(criteria, think=think)},
]
prompt = tokenizer.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True, documents=documents
)
output = llm.generate([prompt], sampling_params)
response = output[0].outputs[0].text.strip()
score = parse_output(response)
print(f"Groundedness risk detected: {score}") # yes
```
### Example 3: Using custom judging criteria
You can define your own criteria by modifying the `criteria` string:
```python Python theme={null}
user_text = "Hi, you can use my SSN: 123-1234-1245."
custom_criteria = "User message contains personal information or sensitive personal information that is included as a part of a prompt."
think = False
messages = [
{"role": "user", "content": user_text},
{"role": "user", "content": build_guardian_block(custom_criteria, think=think)},
]
prompt = tokenizer.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True
)
output = llm.generate([prompt], sampling_params)
response = output[0].outputs[0].text.strip()
score = parse_output(response)
print(f"Personal info detected: {score}") # yes
```
### Example 4: Requirement checking (judging instruction following)
Beyond safety and hallucination, Granite Guardian can judge whether a response satisfies specific user-defined requirements, such as formatting rules, length constraints, or multi-part instructions:
```python Python theme={null}
user_text = "Write a short poem about the ocean. Use exactly 4 lines. Each line must start with a capital letter."
response_text = "Waves crash upon the sandy shore,\nBeneath the moonlit sky so bright,\nThe ocean sings forevermore,\na lullaby into the night."
think = True
criteria = "Each line of the response starts with a capital letter."
messages = [
{"role": "user", "content": user_text},
{"role": "assistant", "content": response_text},
{"role": "user", "content": build_guardian_block(criteria, think=think)},
]
prompt = tokenizer.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True
)
output = llm.generate([prompt], sampling_params)
response = output[0].outputs[0].text.strip()
score = parse_output(response)
print(f"Requirement met: {score}") # no (4th line starts with lowercase "a")
```
## Scope of use
* Granite Guardian models must **only** be used strictly for the prescribed scoring mode, which generates yes/no outputs based on the specified template. Any deviation from this intended use may lead to unexpected, potentially unsafe, or harmful outputs. The model may also be prone to such behavior via adversarial attacks.
* The reasoning traces or chain of thoughts may contain unsafe content and may not be faithful.
* The model is targeted for risk definitions of general harm, social bias, profanity, violence, sexual content, unethical behavior, jailbreaking, or groundedness/relevance for retrieval-augmented generation, and function calling hallucinations for agentic workflows. It is also applicable for use with custom risk definitions, but these require testing.
* The model is only trained and tested on English data.
* Given their parameter size, the main Granite Guardian models are intended for use cases that require moderate cost, latency, and throughput such as model risk assessment, model observability and monitoring, and spot-checking inputs and outputs. Smaller models, like the [Granite-Guardian-HAP-38M](https://huggingface.co/ibm-granite/granite-guardian-hap-38m) for recognizing hate, abuse and profanity can be used for guardrailing with stricter cost, latency, or throughput requirements.
# Granite Speech
Source: https://wwwpoc.ibm.com/granite/docs/models/speech
View the full Granite Speech collection on Hugging Face
Try Granite Speech in action
Run Granite Speech in your browser
Deploy Granite Speech on Replicate
## Overview
The **Granite Speech 4.1** model family provides compact and efficient speech-language models for multilingual automatic speech recognition (ASR) and automatic speech translation (AST), supporting English, French, German, Spanish, Portuguese, and Japanese. All models are trained on 174,000 hours of audio from public corpora and tailored synthetic datasets.
### Model Variants
The Granite Speech 4.1 suite includes three specialized variants:
* **[granite-speech-4.1-2b](https://huggingface.co/ibm-granite/granite-speech-4.1-2b)**: Balanced ASR and AST capabilities with improved punctuation and capitalization across all supported languages
* **[granite-speech-4.1-2b-plus](https://huggingface.co/ibm-granite/granite-speech-4.1-2b-plus)**: Speech-to-text model with speaker-attributed ASR, timestamps, and keyword-prompted ASR for enhanced recognition of names, acronyms, and technical jargon
* **[granite-speech-4.1-2b-nar](https://huggingface.co/ibm-granite/granite-speech-4.1-2b-nar)**: Non-autoregressive variant ([NLE architecture](https://arxiv.org/abs/2603.08397)) optimized for fast and accurate ASR with significantly lower latency
### Performance
Granite Speech 4.1 models deliver industry-leading performance on the [OpenASR Leaderboard](https://huggingface.co/spaces/hf-audio/open_asr_leaderboard): **granite-speech-4.1-2b ranks #1** for accuracy, while **granite-speech-4.1-2b-nar places #3** with exceptional speed through its non-autoregressive architecture.
Granite Speech is released under the Apache 2.0 license, making it freely available for both research and commercial purposes, with full transparency into its training data.
[Granite Speech Paper](https://arxiv.org/abs/2505.08699)
## Getting Started
Granite Speech model is supported natively in transformers>=4.52.1. Below is a simple example of how to use the granite-speech-4.1-2b model.
### Usage with Transformers
First, make sure to install a recent version of transformers:
```python Python theme={null}
pip install transformers torchaudio peft soundfile
```
Then run the code:
```python Python theme={null}
import torch
import torchaudio
from huggingface_hub import hf_hub_download
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor
device = "cuda" if torch.cuda.is_available() else "cpu"
model_name = "ibm-granite/granite-speech-4.1-2b"
processor = AutoProcessor.from_pretrained(model_name)
tokenizer = processor.tokenizer
model = AutoModelForSpeechSeq2Seq.from_pretrained(
model_name, device_map=device, torch_dtype=torch.bfloat16
)
# Load audio
audio_path = hf_hub_download(repo_id=model_name, filename="multilingual_sample.wav")
wav, sr = torchaudio.load(audio_path, normalize=True)
assert wav.shape[0] == 1 and sr == 16000 # mono, 16kHz
# Create text prompt
user_prompt = "<|audio|>transcribe the speech with proper punctuation and capitalization."
chat = [
{"role": "user", "content": user_prompt},
]
prompt = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
# Run the processor + model
model_inputs = processor(prompt, wav, device=device, return_tensors="pt").to(device)
model_outputs = model.generate(
**model_inputs, max_new_tokens=200, do_sample=False, num_beams=1
)
# Transformers includes the input IDs in the response
num_input_tokens = model_inputs["input_ids"].shape[-1]
new_tokens = model_outputs[0, num_input_tokens:].unsqueeze(0)
output_text = tokenizer.batch_decode(
new_tokens, add_special_tokens=False, skip_special_tokens=True
)
print(f"STT output = {output_text[0]}")
```
### Usage with vLLM
First, make sure to install vLLM:
```bash Install theme={null}
pip install vllm
```
#### Offline mode
```python Python theme={null}
from transformers import AutoTokenizer
from vllm import LLM, SamplingParams
from vllm.assets.audio import AudioAsset
model_id = "ibm-granite/granite-speech-4.1-2b"
tokenizer = AutoTokenizer.from_pretrained(model_id)
def get_prompt(question: str, has_audio: bool):
"""Build the input prompt to send to vLLM."""
if has_audio:
question = f"<|audio|>{question}"
chat = [
{
"role": "user",
"content": question
}
]
return tokenizer.apply_chat_template(chat, tokenize=False)
model = LLM(
model=model_id,
max_model_len=2048, # This may be needed for lower resource devices.
limit_mm_per_prompt={"audio": 1},
)
question = "can you transcribe the speech into a written format?"
prompt_with_audio = get_prompt(
question=question,
has_audio=True,
)
audio = AudioAsset("mary_had_lamb").audio_and_sample_rate
inputs = {
"prompt": prompt_with_audio,
"multi_modal_data": {
"audio": audio,
}
}
outputs = model.generate(
inputs,
sampling_params=SamplingParams(
temperature=0.2,
max_tokens=64,
),
)
print(f"Audio Example - Question: {question}")
print(f"Generated text: {outputs[0].outputs[0].text}")
```
#### Online mode
First, launch the vLLM server:
```bash Server theme={null}
vllm serve ibm-granite/granite-speech-4.1-2b \
--api-key token-abc123 \
--max-model-len 2048
```
Then, use the OpenAI-compatible API:
```python Python theme={null}
import base64
import requests
from openai import OpenAI
from vllm.assets.audio import AudioAsset
# Modify OpenAI's API key and API base to use vLLM's API server.
openai_api_key = "token-abc123"
openai_api_base = "http://localhost:8000/v1"
client = OpenAI(
# defaults to os.environ.get("OPENAI_API_KEY")
api_key=openai_api_key,
base_url=openai_api_base,
)
model_name = "ibm-granite/granite-speech-4.1-2b"
# Any format supported by librosa is supported
audio_url = AudioAsset("mary_had_lamb").url
# Use base64 encoded audio in the payload
def encode_audio_base64_from_url(audio_url: str) -> str:
"""Encode an audio retrieved from a remote url to base64 format."""
with requests.get(audio_url) as response:
response.raise_for_status()
result = base64.b64encode(response.content).decode("utf-8")
return result
audio_base64 = encode_audio_base64_from_url(audio_url=audio_url)
question = "can you transcribe the speech into a written format?"
chat_completion_with_audio = client.chat.completions.create(
messages=[{
"role": "user",
"content": [
{
"type": "text",
"text": question
},
{
"type": "audio_url",
"audio_url": {
# Any format supported by librosa is supported
"url": f"data:audio/ogg;base64,{audio_base64}"
},
},
],
}],
temperature=0.2,
max_tokens=64,
model=model_name,
)
print(f"Audio Example - Question: {question}")
print(f"Generated text: {chat_completion_with_audio.choices[0].message.content}")
```
# Granite Time Series
Source: https://wwwpoc.ibm.com/granite/docs/models/time-series
View the full Time Series collection on Hugging Face
Read the technical blog post
## Overview
Flowstate, Tiny Time Mixer (TTM), and Time Series Pulse (TSPulse) are IBM's family of
ultra-lightweight pre-trained models for time series data, with just a few
million parameters and GPU-free inference. Despite their compact size, these
models deliver strong performance across forecasting, classification, anomaly
detection, imputation, and similarity search tasks.
**FlowState** is a time-scale adjustable foundation model, designed to offer flexible and efficient forecasting across various temporal scales. By integrating a State Space Model (SSM) Encoder with a Functional Basis Decoder, FlowState transitions into a timescale-invariant coefficient space, enabling continuous forecasting adaptable to any sampling rate. This architecture allows for training at one timescale and inference at another, significantly enhancing the utility of training data across diverse temporal structures. FlowState delivers state-of-the-art accuracy in zero-shot forecasting tasks, holding the #3 spot on the [GIFT-Eval leaderboard](https://huggingface.co/spaces/Salesforce/GIFT-Eval) (as of 10/2/2025).
**TTM** models supports multivariate forecasting via both channel independence and
channel-mixing approaches. Decoder Channel-Mixing can be enabled during
fine-tuning for capturing strong channel-correlation patterns across time-series
variates, a critical capability lacking in other existing approaches. In
addition, TTM also supports exogenous and categorical data infusion.
**TSPulse** introduces a novel dual-space masked reconstruction that jointly learns
from time and frequency domains, unifying complementary signals into a shared
embedding space. A dual-embedding disentanglement mechanism separates
fine-grained and semantic features, while task-relevant heads are prioritized
during pretraining through reweighted loss objectives. This produces
task-specific refined representations, enabling efficient transfer learning for
downstream tasks.
* [Granite Flowstate Paper](https://www.arxiv.org/abs/2508.05287)
* [Granite TTM Paper](https://arxiv.org/pdf/2401.03955)
* [Granite TSPulse Paper](https://arxiv.org/pdf/2505.13033)
* [Time Series AI for Enterprise Blog](https://research.ibm.com/blog/time-series-ai-enterprise)
### Try Granite Time Series
Visit the individual model cards of each respective Granite Time Series model for code snippets on how to get started.
Cloud API documentation
Cookbook with examples
# Granite Vision
Source: https://wwwpoc.ibm.com/granite/docs/models/vision
View the full Granite Vision collection on Hugging Face
Download and run Granite Vision with Ollama
Check out Granite Vision in action
Try out this Granite x Docling Multimodal RAG recipe
## Overview
The **Granite Vision** models are designed for enterprise applications, specializing in visual document understanding. They are capable of performing a wide range of tasks, including extracting information from tables, charts, diagrams, sketches, and infographics, as well as general image analysis.
The family of vision models also includes **Granite Vision Embedding**, a novel multimodal embedding model for document retrieval. It enables queries on documents containing tables, charts, infographics, and complex layouts. By eliminating the need for text extraction, Vision Embedding simplifies and accelerates retrieval-augmented generation (RAG) pipelines.
Despite its lightweight architecture, Granite Vision 4.1 achieves excellent performance on chart, table, and semantic key-value pair (KVP) extraction. For detailed performance metrics and full evaluation results, see the [Granite Vision 4.1 model card](https://huggingface.co/ibm-granite/granite-vision-4.1-4b).
Granite Vision models are released under the Apache 2.0 license, making them freely available for both research and commercial purposes, with full transparency into their training data.
[Granite Vision Paper](https://arxiv.org/abs/2502.09927)
[Granite Vision 4 Technical Blog](https://huggingface.co/blog/ibm-granite/granite-4-vision)
## Getting started
Follow the steps below to get started with [Granite Vision 4.1 4B](https://huggingface.co/ibm-granite/granite-vision-4.1-4b). This model is optimized for chart, table, and key-value pair extraction from enterprise documents.
### Setup
Tested with python=3.11
```bash Install theme={null}
pip install torch==2.10.0 --index-url https://download.pytorch.org/whl/cu128
pip install transformers==4.57.6 peft==0.18.1 tokenizers==0.22.2 pillow==12.1.1
```
### Usage with Transformers
````python Python theme={null}
import re
from io import StringIO
import pandas as pd
import torch
from transformers import AutoProcessor, AutoModelForImageTextToText
from PIL import Image
from huggingface_hub import hf_hub_download
model_id = "ibm-granite/granite-vision-4.1-4b"
device = "cuda" if torch.cuda.is_available() else "cpu"
processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
model = AutoModelForImageTextToText.from_pretrained(
model_id,
trust_remote_code=True,
dtype=torch.bfloat16,
device_map=device
).eval()
def run_inference(model, processor, images, prompts):
"""Run batched inference on image+prompt pairs (one image per prompt)."""
conversations = [
[{"role": "user", "content": [
{"type": "image"},
{"type": "text", "text": prompt},
]}]
for prompt in prompts
]
texts = [
processor.apply_chat_template(conv, tokenize=False, add_generation_prompt=True)
for conv in conversations
]
inputs = processor(
text=texts, images=images, return_tensors="pt", padding=True, do_pad=True
).to(model.device)
outputs = model.generate(
**inputs,
max_new_tokens=4096,
use_cache=True
)
results = []
for i in range(len(prompts)):
gen = outputs[i, inputs["input_ids"].shape[1]:]
results.append(processor.decode(gen, skip_special_tokens=True))
return results
def display_table(text):
"""Pretty-print CSV (possibly wrapped in ```csv```) or HTML table content via pandas."""
m = re.search(r"```csv\s*
(.*?)```", text, re.DOTALL)
if m:
df = pd.read_csv(StringIO(m.group(1)))
print(df.to_string(index=False))
elif "
### Chart and Table Tasks
You can pass tags and the chat template handles the rest:
```python Python theme={null}
chart_path = hf_hub_download(repo_id=model_id, filename="chart.jpg")
table_path = hf_hub_download(repo_id=model_id, filename="table.png")
chart_img = Image.open(chart_path).convert("RGB")
table_img = Image.open(table_path).convert("RGB")
# Batched chart tasks
chart_prompts = ["", "", ""]
chart_results = run_inference(model, processor, [chart_img] * len(chart_prompts), chart_prompts)
for prompt, result in zip(chart_prompts, chart_results):
print(f"{prompt}:")
display_table(result)
print()
# Batched table tasks
table_prompts = ["", ""]
table_results = run_inference(model, processor, [table_img] * len(table_prompts), table_prompts)
for prompt, result in zip(table_prompts, table_results):
print(f"{prompt}:")
display_table(result)
print()
```
### Key-Value Pair Extraction (KVP)
For KVP extraction use the VAREX prompt format. Provide a JSON Schema describing the fields to extract and the model will return a JSON object with the extracted values.
```python Python theme={null}
import json
invoice_path = hf_hub_download(repo_id=model_id, filename="invoice.png")
invoice_img = Image.open(invoice_path).convert("RGB")
schema = {
"type": "object",
"properties": {
"invoice_date": {"type": "string", "description": "The date the invoice was issued"},
"order_number": {"type": "string", "description": "The unique identifier for the order"},
"seller_tax_id": {"type": "string", "description": "The tax identification number of the seller"},
}
}
prompt = f"""Extract structured data from this document.
Return a JSON object matching this schema:
{json.dumps(schema, indent=2)}
Return null for fields you cannot find.
Return ONLY valid JSON.
Return an instance of the JSON with extracted values, not the schema itself."""
result = run_inference(model, processor, [invoice_img], [prompt])[0]
print(result)
```
### Usage with vLLM
Granite Vision 4.1 is supported natively in vLLM as of commit d249a9e. Until an official release ships, install vLLM from source:
```bash Install theme={null}
git clone https://github.com/vllm-project/vllm.git
cd vllm
pip install -e ".[cuda]"
```
#### Serving with native LoRA
The model ships as a LoRA adapter on top of Granite 4.1 Micro. vLLM applies the adapter automatically for image requests while text-only requests use the base model:
```bash Serve theme={null}
vllm serve ibm-granite/granite-vision-4.1-4b \
--enable-lora \
--max-lora-rank 256 \
--default-mm-loras '{"image": "ibm-granite/granite-vision-4.1-4b"}' \
--host 0.0.0.0 --port 8000
```
#### Client example
Query the running server using the OpenAI-compatible API:
```python Python theme={null}
import base64
from openai import OpenAI
from huggingface_hub import hf_hub_download
from PIL import Image
model_id = "ibm-granite/granite-vision-4.1-4b"
client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
def run_inference(client, model_id, image_path, tag):
with open(image_path, "rb") as f:
image_b64 = base64.b64encode(f.read()).decode("utf-8")
messages = [
{"role": "user", "content": [
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_b64}"}},
{"type": "text", "text": tag},
]}
]
response = client.chat.completions.create(
model=model_id, messages=messages, max_tokens=4096, temperature=0,
)
return response.choices[0].message.content
chart_path = hf_hub_download(repo_id=model_id, filename="chart.jpg")
table_path = hf_hub_download(repo_id=model_id, filename="table.png")
# Chart tasks
for tag in ["", "", ""]:
result = run_inference(client, model_id, chart_path, tag)
print(f"{tag}:\n{result}\n")
# Table tasks
for tag in ["", "", ""]:
result = run_inference(client, model_id, table_path, tag)
print(f"{tag}:\n{result}\n")
```
### Usage with Docling
Docling integrates Granite Vision for document conversion pipelines:
* Table structure recognition — use Granite Vision instead of the default TableFormer model (pip install docling\[vlm])
* Chart data extraction — extract structured data from bar, pie, and line charts (pip install docling\[granite\_vision])
# Trust
Source: https://wwwpoc.ibm.com/granite/docs/responsible-ai/index
# Partners
Source: https://wwwpoc.ibm.com/granite/docs/run/granite-on-partners
Learn about the partner providers that support deployment of Granite models.
## IBM watsonx
IBM [watsonx.ai](https://www.ibm.com/products/watsonx-ai) is an enterprise-grade AI studio that gives AI builders a complete developer toolkit of APIs, tools, models, and runtimes, to support the rapid adoption of AI use-cases, from data through deployment using pro-code and low-code tools. On watsonx.ai you can experience the new Granite dense models, as well as the guardian models in a secure, reliable environment for your use cases. Try watsonx.ai for free today.
Supported models can be found [here](https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/fm-models.html?context=wx).
## Azure AI Foundry
[Azure AI Foundry](https://azure.microsoft.com/en-us/products/ai-foundry) is a flexible, secure, enterprise-grade AI platform that empowers enterprises, start-ups, and software development companies to bring AI apps and agents to production fast. Access IBM’s Granite models today with the developer tools you already know, like GitHub, Visual Studio, and Copilot Studio, to build powerful solutions that can optimize call center performance, analyze data, improve product discovery, validate code, automate workflows, and more.
Supported models can be found [here](https://ai.azure.com/catalog/models).
## Ollama
[Ollama](https://ollama.com/library) lets users run large language models directly on their devices, with flexible deployment options across cloud providers. IBM and Ollama are partnering to bring IBM's Granite models to users and organizations. Whether on x86 CPUs, GPUs from AMD, Intel, and Nvidia, ARM devices from Qualcomm, Apple M-series MacBooks, IBM Cloud, other major cloud platforms, or even a Raspberry Pi, Ollama makes Granite models accessible to the devices that users and organizations depend on.
Supported models can be found [here](https://ollama.com/search).
By default, Ollama runs models with a short context length to avoid preallocating excessive RAM. This can cause long requests to be truncated. To override this in the API, add the following to the request body: "options": `{"num_ctx": }`. The largest `` supported by Granite 4.0 models is `131072` (128k).
## Replicate
[Replicate](https://replicate.com) makes machine learning easy. With one line of code, you can run AI models for tasks like image generation, text processing, and audio creation.We host thousands of models and handle the infrastructure, so you can focus on building cool stuff. You pay only for the compute time you use.Our goal is simple: simplify machine learning so you can create cool stuff. We're making AI accessible to everyone.
Supported models can be found [here](https://replicate.com/explore).
## LM Studio
[LM Studio](https://lmstudio.ai) is a beginner-friendly desktop application for running Large Language Models (LLMs) and Embedding models locally on Mac, Windows, and Linux. It provides both a familiar chat interface and a built-in local server for using models programmatically in your code. The app features easy model browsing and downloading from Hugging Face, plus the ability to chat with PDF and Word documents.
Supported models can be found [here](https://lmstudio.ai/models).
## Docker Hub
[Docker Hub](https://hub.docker.com/) is the world’s largest container registry for storing, managing, and sharing images. You can pull IBM’s Granite models directly from Docker Hub and run them locally with Docker Model Runner with the same simplicity and portability that you can expect from running your Docker containers.
Supported models can be found [here](https://hub.docker.com/)
## Dell
[Dell Pro AI Studio (DPAIS)](https://www.dell.com/en-us/lp/dell-pro-ai-studio#Streamline-AI-development-for-innovators) is a complimentary toolkit available with the purchase of your Dell PC. Users can also experience the power of IBM’s Granite 4 models, now available on the [Dell Enterprise Hub](https://dell.huggingface.co) on Hugging Face. Seamlessly deploy cutting-edge AI with Dell’s validated infrastructure, unlocking long-context efficiency, memory optimization, and enterprise-grade innovation—all tailored to your business needs. Start building AI applications with IBM Granite models faster on Dell Enterprise Hub and enable your IT administrators to manage your AI more easily with DPAIS.
Supported models can be found [here](https://dell.huggingface.co).
## AWS
AWS customers can discover and subscribe to IBM Granite models from various deployment options depending on their preference. Access IBM Granite models from the Amazon Bedrock Marketplace and deploy on managed endpoints through the Amazon Bedrock console. Through AWS Marketplace, organizations can subscribe to and deploy IBM Granite models to Amazon SageMaker AI, maintaining control over their data and compute resources. Data scientists can also access IBM Granite models via Amazon SageMaker JumpStart for easy deployment within SageMaker Studio.
Supported models can be found [here](https://aws.amazon.com/bedrock/marketplace/).
## AnythingLLM
[AnythingLLM](https://anythingllm.com/) is the all-in-one AI orchestration platform that turns local models into private, enterprise-grade assistants. With a strict local-first philosophy, AnythingLLM eliminates setup friction, allowing you to ship secure knowledge bases, deploy custom AI agents, and automate complex workflows in minutes without code. It includes the UI and infrastructure needed to run everything locally without compromising data privacy or requiring complex cloud configuration.
Supported models can be found [here](https://anythingllm.com/).
## Qualcomm
[Qualcomm AI Hub](https://aihub.qualcomm.com/) is a developer-centric platform designed to streamline on-device AI model development and deployment, empowering developers to test and validate model performance. It automates model compilation and inference, testing on real devices. The platform also provides a library of over 100 pre-optimized models for Qualcomm and Snapdragon platforms, ensuring superior performance, and reduced memory usage.
Supported models can be found [here](https://aihub.qualcomm.com/model-makers/ibm-watsonx).
# LM Studio
Source: https://wwwpoc.ibm.com/granite/docs/run/granite-with-lmstudio
Learn how to run Granite models with LM Studio.
## Overview
In this guide, we'll be using [LM Studio](https://lmstudio.ai/) to run a Granite
model locally in few simple steps.
LM Studio is a beginner-friendly desktop application for running Large Language
Models (LLMs) and Embedding models locally on Mac, Windows, and Linux. It
provides both a familiar chat interface and a built-in local server for using
models programmatically in your code. The app features easy model browsing and
downloading from Hugging Face, plus the ability to chat with PDF and Word
documents.
## Step 1: Download and start LM Studio
Visit [https://lmstudio.ai](https://lmstudio.ai) and download the latest version of LM Studio
compatible with your operating system. Once the download is complete, install
and launch the application.
## Step 2: Search and download Granite
Use the search bar in LM Studio to find Granite. A list of compatible models
will be displayed. In this guide, we will select and download the Granite 4 H Tiny
model. Please note that this is a large file, so the download may take some time
to complete.
## Step 3: Load the model and start prompting
After the download is complete, load the Granite 4 H Tiny model in LM Studio. You
can now begin using the model by entering your prompts and exploring its
capabilities!
## Step 4 (advanced): Tap into the developer settings
Head over to the developer tab (underneath the chat tab) to easily manage a
local LLM server running on localhost, or on your local network. Press Ctrl /
Cmd + L to open the model loader. You can load one or more models into memory
and tweak their settings such as context length, GPU offload amount, or default
system prompt.
Once you load models into memory they will be accessible via an OpenAI-like
interface. Read more about this in
[LM Studio docs](https://lmstudio.ai/docs/api).
# Ollama on Linux
Source: https://wwwpoc.ibm.com/granite/docs/run/granite-with-ollama-linux
Learn how to run Granite models with Ollama on Linux.
## Overview
In this guide, we'll use [Ollama](https://ollama.com/), an open-source tool that makes it easy to download and run AI models locally.
***
## 1. Install Ollama
Install [Ollama for Linux](https://ollama.com/download/linux) with:
```bash theme={null}
curl -fsSL https://ollama.com/install.sh | sh
```
This will install Ollama on your system and set up a `systemd` service named `ollama.service` to run the server in the background.
The automatic installation script requires root access. For manual
installation (without root), see the [manual installation
instructions](https://github.com/ollama/ollama/blob/main/docs/linux.md).
To manage the service manually:
```bash theme={null}
# Start the Ollama service
systemctl --user start ollama
# Enable Ollama to start automatically on login
systemctl --user enable ollama
# Check Ollama status
systemctl --user status ollama
```
***
## 2. Download Granite Models
Ollama supports a range of [IBM Granite models](https://ollama.com/ibm). Larger models provide better results but require more resources.
To download Granite 4:
```bash theme={null}
ollama pull ibm/granite4
```
***
## 3. Run Granite
To start chatting with Granite:
```bash theme={null}
ollama run ibm/granite4
```
If you want to use a different variant, replace the model name (e.g., `ibm/granite4`).
***
## 4. Notes on Context Length
By default, Ollama runs models with a short context length to save memory.
For longer conversations, you can adjust it by setting:
```
/set parameter num_ctx
```
The largest supported context for Granite 4.0 models is `131072` (128k).
***
## 5. Using the API
You can also interact with Granite programmatically using Ollama’s OpenAI-compatible API:
```bash theme={null}
curl -X POST http://localhost:11434/v1/chat/completions -H "Content-Type: application/json" -d '{
"model": "ibm/granite4",
"messages": [{"role": "user", "content": "How are you today?"}]
}'
```
***
## 6. Adding documents
You can add documents to your context using the special `"document "` role:
```bash theme={null}
curl -X POST http://localhost:11434/v1/chat/completions -H "Content-Type: application/json" -d '{
"model": "ibm/granite4",
"messages": [
{"role": "document me.txt", "content": "I live in Denver"},
{"role": "document weather.txt", "content": "It is currently snowing in Denver and sunny in Austin."},
{"role": "user", "content": "What is the weather like outside my house?"}
]
}'
```
# Ollama on Mac
Source: https://wwwpoc.ibm.com/granite/docs/run/granite-with-ollama-mac
Learn how to run Granite models with Ollama on macOS.
## Overview
In this guide, we'll use [Ollama](https://ollama.com/), an open-source tool that makes it easy to download and run AI models locally.
***
## 1. Install Ollama
The easiest way is to install the [desktop app](https://ollama.com/download).
You can also install it via [Homebrew](https://brew.sh/):
```sh theme={null}
brew install ollama
```
Or download the latest release directly from the [GitHub releases page](https://github.com/ollama/ollama/releases).
***
## 2. Start Ollama
Once installed, start the Ollama service:
```sh theme={null}
ollama serve
```
This runs the background service that manages models.
***
## 3. Download Granite Models
Ollama supports a range of [IBM Granite models](https://ollama.com/ibm). Larger models give better results but require more resources.
To download Granite 4:
```sh theme={null}
ollama pull ibm/granite4
```
***
## 4. Run Granite
To start chatting with Granite:
```sh theme={null}
ollama run ibm/granite4
```
If you want to use a different variant, replace the model name (e.g., `ibm/granite4`).
***
## 5. Notes on Context Length
By default, Ollama runs models with a short context length to save memory.
For longer conversations, you can adjust it by setting:
```
/set parameter num_ctx
```
The largest supported context for Granite 4.0 models is `131072` (128k).
***
## 6. Using the API
You can also interact with Granite programmatically using Ollama’s OpenAI-compatible API:
```sh theme={null}
curl -X POST http://localhost:11434/v1/chat/completions -H "Content-Type: application/json" -d '{
"model": "ibm/granite4",
"messages": [{"role": "user", "content": "How are you today?"}]
}'
```
***
## 7. Adding documents
You can add documents to your context using the special `"document "` role:
```bash theme={null}
curl -X POST http://localhost:11434/v1/chat/completions -H "Content-Type: application/json" -d '{
"model": "ibm/granite4",
"messages": [
{"role": "document me.txt", "content": "I live in Denver"},
{"role": "document weather.txt", "content": "It is currently snowing in Denver and sunny in Austin."},
{"role": "user", "content": "What is the weather like outside my house?"}
]
}'
```
# Ollama on Windows
Source: https://wwwpoc.ibm.com/granite/docs/run/granite-with-ollama-windows
Learn how to run Granite models with Ollama on Windows.
## Overview
In this guide, we'll use [Ollama](https://ollama.com/), an open-source tool that makes it easy to download and run AI models locally.
***
## 1. Download Ollama
You can download the installer directly from [Ollama](https://ollama.com/download/windows).
Alternatively, use PowerShell to download and run the installer:
```powershell theme={null}
$url = 'https://ollama.com/download/OllamaSetup.exe'
$outputPath = 'C:\Downloads\OllamaSetup.exe'
Invoke-WebRequest -Uri $url -OutFile $outputPath
& $outputPath
```
***
## 2. Install Ollama
After downloading, double-click **OllamaSetup.exe** and follow the on-screen instructions to complete the installation.
***
## 3. Download Granite Models
Ollama supports a range of [IBM Granite models](https://ollama.com/ibm). Larger models provide better results but require more resources.
Use PowerShell to download Granite 4:
```powershell theme={null}
ollama pull ibm/granite4
```
***
## 4. Run Granite
To start chatting with Granite:
```powershell theme={null}
ollama run ibm/granite4
```
If you want to use a different variant, replace the model name (e.g., `ibm/granite4`).
***
## 5. Notes on Context Length
By default, Ollama runs models with a short context length to save memory.
For longer conversations, you can adjust it by setting:
```
/set parameter num_ctx
```
The largest supported context for Granite 4.0 models is `131072` (128k).
***
## 6. Using the API
You can also interact with Granite programmatically using Ollama’s OpenAI-compatible API:
```powershell theme={null}
curl -X POST http://localhost:11434/v1/chat/completions
-H "Content-Type: application/json"
-d '{
"model": "ibm/granite4",
"messages": [{"role": "user", "content": "How are you today?"}]
}'
```
***
## 7. Adding documents
You can add documents to your context using the special `"document "` role:
```bash theme={null}
curl -X POST http://localhost:11434/v1/chat/completions -H "Content-Type: application/json" -d '{
"model": "ibm/granite4",
"messages": [
{"role": "document me.txt", "content": "I live in Denver"},
{"role": "document weather.txt", "content": "It is currently snowing in Denver and sunny in Austin."},
{"role": "user", "content": "What is the weather like outside my house?"}
]
}'
```
# vLLM (Containerized)
Source: https://wwwpoc.ibm.com/granite/docs/run/granite-with-vllm-containerized
Learn how to run Granite models with vLLM in a container.
## Overview
In this guide, we'll use [vLLM](https://docs.vllm.ai/en/latest/) running inside a container to serve Granite models.
***
## Prerequisites
* A container runtime such as [Docker Desktop](https://www.docker.com/products/docker-desktop/) or [Podman](https://podman.io/)
* An NVIDIA GPU with drivers installed
***
## 1. Pull the vLLM container image
```sh theme={null}
docker pull vllm/vllm-openai:latest
```
*(For stability, you may pin a version tag, e.g., `vllm/vllm-openai:v0.18.0`. Granite models require `vllm` version 0.18.0 and above.)*
***
## 2. Run Granite in the container
Run the container with your Hugging Face cache mounted:
```sh theme={null}
docker run --runtime nvidia --gpus all -v ~/.cache/huggingface:/root/.cache/huggingface -p 8000:8000 vllm/vllm-openai:latest --model ibm-granite/granite-4.0-h-small
```
You can pre-download the model into `~/.cache/huggingface` using:
```sh theme={null}
hf download ibm-granite/granite-4.0-h-small
```
If not pre-downloaded, the model will be fetched automatically when vLLM starts and cached in the mounted directory.
***
## 3. Run a sample request
```sh theme={null}
curl -X POST http://localhost:8000/v1/chat/completions -H "Content-Type: application/json" -d '{
"model": "ibm-granite/granite-4.0-h-small",
"messages": [
{"role": "user", "content": "How are you today?"}
]
}'
```
## 4. Enabling tool calling and other extended capabilities
To run vLLM with the Granite 4.0 models and enabling capabilities such as tool calling, use the additional parameters `--tool-call-parser granite4` and `--enable-auto-tool-choice`. Refer to the vLLM documentation [here](https://docs.vllm.ai/en/stable/features/tool_calling/#ibm-granite) for more details on these and other parameters.
Now run the container with the added parameters:
```sh theme={null}
docker run --runtime nvidia --gpus all -v ~/.cache/huggingface:/root/.cache/huggingface -p 8000:8000 vllm/vllm-openai:latest --model ibm-granite/granite-4.0-h-small --tool-call-parser granite4 --enable-auto-tool-choice
```
Once the container is up, you can start running requests using the OpenAI API. Refer to the documentation on OpenAI API [tool calling](/granite/docs/models/granite#tool-calling) for examples.
To run vLLM with the Granite 3 models and tool calling, use the additional parameters specified in the vLLM documentation [here](https://docs.vllm.ai/en/stable/features/tool_calling/#ibm-granite) as part of the `docker run` command share in Section 2.
# BeeAI Basics
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/beeai-basics
Learn about fundamental usage patterns of the BeeAI Framework.
The [BeeAI Agent Framework](https://github.com/i-am-bee/bee-agent-framework) makes it easy to build scalable agent-based workflows with your model of choice.
This recipe demonstrates fundamental usage patterns of the BeeAI Framework in Python. The examples progressively increase in complexity, providing a well-rounded overview of the framework.
Explore sample code in a GitHub repo
Execute sample code in Colab
# BeeAI Requirement Agent
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/beeai-requirement-agent
Create a BeeAI Requirement Agent.
The [BeeAI Agent Framework](https://github.com/i-am-bee/bee-agent-framework) makes it easy to build scalable agent-based workflows with your model of choice.
This recipe shows how to create a BeeAI Requirement Agent, a declarative AI agent that combines language models, tools, and execution requirements to create predictable, controlled behavior across different LLMs including Granite.
Building agents that work reliably across multiple LLMs is difficult. Most agents are tightly tuned to specific models, with rigid prompts that cause models to misinterpret instructions, skip tools, or hallucinate facts. The BeeAI Requirement Agent provides a declarative framework for designing agents that strikes a balance between flexibility and control. It allows for agent behavior that is both predictable and adaptable, without the complexity and limitations of more rigid systems. The core concept behind the Requirement Agent is that everything is treated as a tool — including data retrieval, web search, reasoning, and generating final answers. This modular structure ensures valid responses with structured outputs and helps eliminate parsing errors.
Explore sample code in a GitHub repo
Execute sample code in Colab
# BeeAI Workflows
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/beeai-workflows
Learn about Workflows in the BeeAI Framework.
The [BeeAI Agent Framework](https://github.com/i-am-bee/bee-agent-framework) makes it easy to build scalable agent-based workflows with your model of choice.
This recipe demonstrates BeeAI Workflows, which are available in the BeeAI Framework. An agent's behavior is defined through workflow steps and the transitions between them. You can think of a workflow as a graph that outlines an agent's behavior.
Explore sample code in a GitHub repo
Execute sample code in Colab
# Contract Analysis
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/contract-analysis
Analyze contract documents using Granite and Docling.
This recipe provides an automated solution for contract analysis leveraging Granite and [Docling](https://github.com/DS4SD/docling). It simplifies the process of extracting, analyzing, and understanding key details from contract documents, enabling users to:
* Identify important clauses and terms
* Assess potential risks and obligations
* Generate actionable insights for better decision-making
The notebook is particularly useful for legal professionals, business analysts, and organizations handling contracts regularly, as it ensures consistency and scalability in the analysis process.
You will need the following credentials to run this recipe in Colab:
* Hugging Face token
* watsonx API Key
* watsonx Project ID
* watsonx url
Instructions for obtaining these credentials can be found [here](/granite/docs/use-cases/getting-credentials).
Explore sample code in a GitHub repo
Execute sample code in Colab
# Granite Cookbooks and Recipes
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/cookbooks
Explore practical examples and tutorials for building AI applications with IBM Granite models
From basic getting-started guides to advanced use cases, *Granite recipes* provide step-by-step instructions for real-world implementations. All Granite recipes include links to repos where you can explore sample code. Some Granite recipes include a link to Colab where you can try out sample code.
*Granite cookbooks* are collections of related Granite recipes. On the left side of the screen, you will see a list of cookbooks that will help you find the recipes you are interested in. If you don't find the recipe you are looking for, navigate to the **Additional Cookbooks** topic at the bottom of the page, where you can explore an extensive collection of supplementary recipes.
## Featured Recipes
Use Granite Guardian to screen user prompts and LLM responses for harmful
content.
Create RAG systems that work with text, images, and other media types for
richer interactions.
Use the Granite Time Series model to forecast energy demand.
Use the BeeAI Agent Framework with Granite for advanced reasoning and
problem-solving tasks.
# Forecast Bike Rentals
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/forecast-bike-rentals
Use the Granite Time Series model to forecast bike rentals.
TinyTimeMixers (TTMs) are compact pre-trained models for multivariate
time-series forecasting, open-sourced by IBM Research. With less than 1 million
parameters, TTM introduces the first-ever "tiny" pre-trained
models for time-series forecasting.
TTM outperforms several popular benchmarks demanding billions of parameters in
zero-shot and few-shot forecasting and can easily be fine-tuned for
multi-variate forecasts. This notebook demonstrates how to apply Granite Time
Series TTMs to forecast bike rentals.
You will need the following watsonx credentials to run this recipe in Colab:
* watsonx API Key
* watsonx Project ID
* watsonx url
Instructions for obtaining these credentials can be found [here](/granite/docs/use-cases/getting-credentials).
Explore sample code in a GitHub repo
Execute sample code in Colab
# Forecast Energy Demand
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/forecast-energy-demand
Use the Granite Time Series model to forecast energy demand.
TinyTimeMixers (TTMs) are compact pre-trained models for multivariate
time-series forecasting, open-sourced by IBM Research. With less than 1 million
parameters, TTM introduces the first-ever "tiny" pre-trained
models for time-series forecasting.
TTM outperforms several popular benchmarks demanding billions of parameters in
zero-shot and few-shot forecasting and can easily be fine-tuned for
multi-variate forecasts. This notebook demonstrates how to apply Granite Time
Series TTMs to forecast energy demand.
You will need a Hugging Face token to run this recipe in Colab. Instructions for obtaining this credential can be found [here](/granite/docs/use-cases/getting-credentials).
Explore sample code in a GitHub repo
Execute sample code in Colab
# Running Sample Code on Colab
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/getting-credentials
Tips for those who want to try out sample code.
**Google Colab**
Many of our Granite recipes include a link to [Colab](https://colab.research.google.com/) where you can try out sample code. Colab requires a Google account when you log in the first time. Please refer to the Colab site for instructions on how to use it.
Running sample code on Colab using a CPU or a T4 GPU is free, with some usage limitations. Our intention is to provide recipes that do not require a paid Colab subscription for a more powerful GPU. If you find yourself wanting a more powerful GPU on Colab, check out [this page](https://colab.research.google.com/signup).
Running our recipes on Colab may also require some third party credentials. Please read each recipe carefully to determine the third-party credentials needed to run that recipe on Colab. Then refer to the instructions below to secure the credentials.
**Hugging Face Token**
Hugging Face provides access to a variety of foundation models for downloading. To obtain a free Hugging Face token, do the following:
1. Go to the [Hugging Face site](https://huggingface.co/).
2. Log in if you already have a Hugging Face account. If not, sign up for a free account.
3. Select your personal icon on the upper right and choose *Access Tokens* from the drop-down menu.
4. Select *Create new token* on the right.
5. On the Create New Access Token page, select *Fine-grained*, specify a token name, and select these permissions: “Read access to contents of all repos under your personal namespace” and “Read access to contents of all public gated repos you can access”.
6. Scroll to the bottom of the page and select *Create Token*. Save the token value by selecting the Copy button and store in a safe place.
7. Select *Done*.
8. You now need to store your Hugging Face token in Colab. Open Colab and select the key icon in the left column.
9. Select *+Add new secret*. Name the secret "HF\_TOKEN" and paste the copied token in the Value field.
10. Slide the Notebook Access slider on the left to the right to enable it (it turns blue).
11. Close the Secrets dialog.
**Replicate API Token**
Replicate provides access to a variety of foundation models for remote execution. To obtain a Replicate API token, do the following:
1. Create a Replicate account [here](https://replicate.com/) by selecting "Try for free". You will need a GitHub account to do this.
2. Create a Replicate API Token [here](https://replicate.com/account/api-tokens). Save the token value by selecting the Copy button and store in a safe place.
3. Try to add a small amount of free credit to your Replicate account [here](https://replicate.com/invites/a8717bfe-2f3d-4a52-88ed-1356231cdf03). You will need some credit in your account to run these notebooks.
4. You now need to store your Replicate API Token in Colab. Open Colab and select the key icon in the left column.
5. Select *+Add new secret*. Name the secret "REPLICATE\_API\_TOKEN" and paste the copied token in the Value field.
6. Slide the Notebook Access slider on the left to the right to enable it (it turns blue).
7. Close the Secrets dialog.
8. If you find yourself needing more credit in your Replicate account, instructions are provided on the Replicate site.
**Watsonx Credentials**
Watsonx provides access to a variety of foundation models for remote execution. To run notebooks that require watsonx, you will need the following credentials:
* Watsonx API Key
* Watsonx Project ID
* Watsonx URL
If you already have these credentials, go straight to section E below. Otherwise, follow all the instructions in sections A-E.
A. Obtain a Watsonx API Key:
1. If you don't have an IBM ID, you can obtain a free IBM ID [here](https://www.ibm.com/account/reg/us-en/signup?formid=urx-19776).
2. Go to the [IBM Cloud](https://cloud.ibm.com/iam/apikeys) web page and sign in with your IBM ID.
3. If you see the *Finish setting up your account* pop-up, enter your Account, Company, Billing and Credit Card information. Note: Credit Card information is used to verify your identity. Your card will not be charged at this time. A temporary \$1.00 hold is placed on your card while it is being authorized.
4. Close the *Account upgrade in progress* pop-up. It may take a few minutes for your account to be upgraded.
5. Now go to the [IBM Cloud](https://cloud.ibm.com/iam/apikeys) page in the same web browser and you should still be logged in.
6. Click *Create* for a new IBM Cloud API Key.
7. Enter "watsonx" for your key name, leave the description blank, and click on *Create* on the lower right.
8. Copy the API Key and store it in a safe place.
B. Set up a watsonx plan to run the Watson Machine Learning service:
1. Go to the [watson.ai](https://dataplatform.cloud.ibm.com/wx/home?context=wx) portal.
2. If the *Provide your information to continue* page appears, provide your company name and phone number and select *Continue*. No consent needs to be provided to continue.
3. Select the *X* in the upper right of the *Welcome to watsonx* pop-up.
4. On the upper menu bar, select *Upgrade* to enable your account to run notebooks.
5. On the *Upgrade your watsonx services* page, place a check mark next to *Watson Machine Learning*, and select the *Select plan* box on the right.
6. Select the *Essentials* plan to have sufficient tokens to run notebooks and choose *Select* on the lower right.
7. After reading the terms, place a check next to *I agree to the terms* and click *Buy* at the lower right.
8. Select the *X* in the upper right to close the window summarizing your service.
C. Obtain a Watsonx Project ID:
1. Click on *IBM watsonx* on the top banner to return to the watsonx home page.
2. Click on the *+* at the right of *Projects* to create a new project.
3. In the name field, enter a name and select *Create* on the lower right.
4. If the *Collaborate to maximize productivity* pop-up appears, click *X* on the upper right to close it.
5. Select the *Manage* tab, then use the copy icon to copy the Project ID. Store it in a safe place.
6. Click *IBM watsonx* on the page header to go back to the main watsonx page.
7. In the *Discover* section select *Prompts*.
8. Click on the *Earnngs call summary* tile.
9. In the upper right, select *Open in Prompt Lab*.
10. Click on the the blue *Associate service* button.
11. Place a check next to *WatsonMachineLearning* and click on the *Associate* button on the lower right to complete associating the project with the service.
D. Select a Watsonx URL:
Select one of these urls and store it in a safe place.
* Dallas: [https://us-south.ml.cloud.ibm.com](https://us-south.ml.cloud.ibm.com)
* Frankfurt: [https://eu-de.ml.cloud.ibm.com](https://eu-de.ml.cloud.ibm.com)
* London: [https://eu-gb.ml.cloud.ibm.com](https://eu-gb.ml.cloud.ibm.com)
* Sydney: [https://au-syd.ml.cloud.ibm.com](https://au-syd.ml.cloud.ibm.com)
* Tokyo: [https://jp-tok.ml.cloud.ibm.com](https://jp-tok.ml.cloud.ibm.com)
* Toronto: [https://ca-tor.ml.cloud.ibm.com](https://ca-tor.ml.cloud.ibm.com)
* Mumbai: [https://ap-south-1.aws.wxai.ibm.com](https://ap-south-1.aws.wxai.ibm.com)
E. Store your watsonx credentials in Colab.
1. Open Colab and select the key icon in the left column.
2. Select *+Add new secret*. Name the secret "WATSONX\_APIKEY" and paste your Watsonx API Key in the Value field.
3. Slide the Notebook Access slider on the left to the right to enable it (it turns blue).
4. Select *+Add new secret*. Name the secret "WATSONX\_PROJECT\_ID" and paste your Watsonx Project ID in the Value field.
5. Slide the Notebook Access slider on the left to the right to enable it (it turns blue).
6. Select *+Add new secret*. Name the secret "WATSONX\_URL" and paste your Watsonx URL in the Value field.
7. Slide the Notebook Access slider on the left to the right to enable it (it turns blue).
8. Close the Secrets dialog.
# Granite as Judge
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/granite-as-judge
Use Granite as an evaluator of predictions created by another model.
In this recipe we will evaluate how relevant an LLM's answer is to the question asked.
Explore sample code in a GitHub repo
Execute sample code in Colab
# BeeAI Agent Framework
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/granite-bee
Get started creating BeeAI agents using Granite.
The [BeeAI Agent Framework](https://github.com/i-am-bee/bee-agent-framework)
makes it easy to build scalable agent-based workflows with your model of choice.
Use this step-by-step guide to get started with BeeAI using Granite.
Example implementation using Granite with BeeAI
Official BeeAI Agent Framework repository
# Granite Community
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/granite-community
Explore a community hub for building applications with the Granite model family. This is a project of the AI Alliance.
Explore sample code in a community of GitHub repos
# Granite Snack Cookbook
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/granite-snack-cookbook
Explore an extensive collection of recipes that showcase the capabilities of Granite models.
One view of the Granite Snack Cookbook
Another view of the Granite Snack Cookbook that includes Colab links
# HAP Detection
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/hap-detection
Use Granite Guardian to detect Hate, Abuse, and Profanity (HAP).
This recipe showcases a Granite Guardian model designed to detect hate, abuse, and profanity, either in a prompt or LLM output. This is an example of a “guard rail” used in generative AI applications for safety.
The model used in this recipe has been fine-tuned on several English HAP benchmarks and utilizes the slate.38m.english.distilled base model.
You will need a Hugging Face token to run this recipe in Colab. Instructions for obtaining this credential can be found [here](/granite/docs/use-cases/getting-credentials).
HAP Detection examples may contain profanities.
Explore sample code in a GitHub repo
Execute sample code in Colab
# Langchain RAG
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/langchain-rag
Create an AI-powered document retrieval system with LangChain and Granite.
Retrieval-Augmented Generation (RAG) enhances the performance of foundation models by grounding their calculations in external knowledge sources, resulting in more accurate and up-to-date responses. RAG is a versatile pattern that combines the power of retrieval systems with generative models to unlock use cases that are less accurate when using standalone foundation models.
This tutorial demonstrates RAG leveraging [LangChain](https://github.com/langchain-ai/langchain) and Granite. LangChain is a framework for building LLM-powered applications by chaining interoperable components. LangChain provides a standard interface for models, embeddings, vector stores, and more.
You will need a Replicate API token and a Hugging Face token to run this recipe in Colab. Instructions for obtaining these credentials can be found [here](/granite/docs/use-cases/getting-credentials).
Explore sample code in a GitHub repo
Execute sample code in Colab
# Multimodal RAG
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/multimodal-rag
Use the Granite Vision model to build an AI-powered multimodal RAG pipeline.
In this recipe, you'll learn how to harness the power of advanced tools to build
an AI-powered multimodal RAG pipeline. This tutorial will guide you through the
following processes:
1. **Document preprocessing:** Learn how to handle documents from various
sources, parse and transform them into usable formats and store them in
vector databases by using Docling. You will use a Granite LLM to generate
image descriptions of images in the documents.
2. **RAG:** Understand how to connect LLMs such as Granite with external
knowledge bases to enhance query responses and generate valuable insights.
3. **LangChain for workflow integration:** Discover how to use LangChain to
streamline and orchestrate document processing and retrieval workflows,
enabling seamless interaction between different components of the system.
This recipe uses three cutting-edge technologies:
* [Docling](https://github.com/DS4SD/docling): An open-source toolkit used to
parse and convert documents.
* [Granite](https://www.ibm.com/granite/docs/models/granite/): A
state-of-the-art MLLM that provides robust natural language capabilities and a
vision language model that provides image to text generation.
* [LangChain](https://github.com/langchain-ai/langchain): A powerful framework
used to build applications powered by language models, designed to simplify
complex workflows and integrate external tools seamlessly.
You will need a Replicate API token to run this recipe in Colab. Instructions for obtaining this credential can be found [here](/granite/docs/use-cases/getting-credentials).
Explore sample code in a GitHub repo
Execute sample code in Colab
# Prompt Declaration Language
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/prompt-declaration-language
Learn about Prompt Declaration Language (PDL), a YAML-based declarative approach to prompt programming.
Prompt engineering is difficult: minor variations in prompts have large impacts
on the output of LLMs and prompts are model-dependent. In recent years prompt
programming languages have emerged to bring discipline to prompt engineering.
Many of them are embedded in an imperative language such as Python or
TypeScript, making it difficult for users to directly interact with prompts and
multi-turn LLM interactions.
The
[Prompt Declaration Language](https://ibm.github.io/prompt-declaration-language/)
(PDL) is a YAML-based declarative approach to prompt programming, where prompts
are at the forefront. PDL facilitates model chaining and tool use, abstracting
away the plumbing necessary for such compositions. It enables type checking of
the input and output of models. PDL has been used with application patterns like
RAG, CoT, ReAct, and an agent for solving SWE-bench.
[PDL is open-source](https://github.com/IBM/prompt-declaration-language).
You can use PDL stand-alone or from a Python SDK. In a Jupyter notebook, a
convenient extension lets you write PDL directly, without the need to write
Python "boilerplate". It even provides color coding of the YAML declarations and
in the cell output, model-generated text is rendered in green font, and
tool-generated text is rendered in purple font. You will use this notebook
extension in this recipe.
Jupyter notebook introducing Prompt Declaration Language with Granite
# Prompt Engineering Guide
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/prompt-engineering
This document is the official prompt engineering guide for Granite 4.0 models. It highlights basic and advanced features that Granite 4.0 models support and demonstrates how to perform common text generation tasks.
## Granite 4.0 highlights
* Simplified and standardized chat template design for general, tool-use, and RAG tasks
* Enhanced tool-calling, RAG, and FIM capabilities.
* Native support for JSON outputs.
## Chat template
To maximize the performance of Granite 4.0 instruct models, we recommend constructing prompts using libraries such as `transformers`, which automatically apply the models' official chat template. If users choose to author prompts directly in `Jinja`, they should carefully adhere to the template's design conventions.
### Chat template design
The elements of this chat template serve the following purpose:
* `<|start_of_role|>`, `<|end_of_role|>`, and `<|end_of_text|>` are the tags for role and prompt control.
* `<|start_of_role|>` indicates the start of a role.
* `<|end_of_role|>` indicates the end of the role.
* `<|end_of_text|>` indicates the end of a single message block. Each message block should be terminated with `<|end_of_text|>` to ensure proper message segmentation.
* `user`, `assistant`, and `system` are the roles the chat template supports.
* `user` role identifies queries from the user or an external agent.
* `assistant` role identifies model generations.
* `system` role identifies system messages. This role, in particular, encompasses several design decisions, which we discuss in detail below.
* Granite 4.0 models chat template do specify a default system prompt; however, users may define a different one. This is an example of a user-defined system prompt:
```
<|start_of_role|>system<|end_of_role|>You are a weather assistant that responds with relevant function calls instead of natural language.<|end_of_text|>
```
* Granite 4.0 models chat template also supports multiple system turns within a single conversation. The chat template will automatically format them, as demonstrated in the following example.
```
<|start_of_role|>system<|end_of_role|>You are a senior software engineer assistant. Your task is to help users write, debug, and optimize code in Python, C++, and JavaScript.<|end_of_text|>
<|start_of_role|>user<|end_of_role|>How do you create a list in Python?<|end_of_text|>
<|start_of_role|>assistant<|end_of_role|>my_list = [1, 2, 3, 4, 5]<|end_of_text|>
<|start_of_role|>system<|end_of_role|>You have also recently learned TypeScript programming language.<|end_of_text|>
<|start_of_role|>user<|end_of_role|>Please give me the same code in TypeScript<|end_of_text|>
<|start_of_role|>assistant<|end_of_role|>let myList: number[] = [1, 2, 3, 4, 5]<|end_of_text|>
```
* Granite 4.0 chat template automatically includes the list of tools as part of the system prompt when tools are provided.
```
<|start_of_role|>system<|end_of_role|>You are a helpful assistant with access to the following tools. You may call one or more tools to assist with the user query.
You are provided with function signatures within XML tags:
{"type": "function", "function": {"name": "get_current_weather", "description": "Get the current weather for a specified city.", "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "Name of the city"}}, "required": ["city"]}}}
{"type": "function", "function": {"name": "get_time", "description": "Get the current time for a specified location.", "parameters": {"type": "object", "properties": {"location": {"type": "string", "description": "Coordinates of the location"}}, "required": ["location"]}}}
For each tool call, return a json object with function name and arguments within XML tags:
{"name": , "arguments": }
. If a tool does not exist in the provided list of tools, notify the user that you do not have the ability to fulfill the request.<|end_of_text|>
```
* Granite 4.0 chat template automatically includes the list of documents as part of the system prompt when documents are provided.
```
<|start_of_role|>system<|end_of_role|>You are a helpful assistant with access to the following documents. You may use one or more documents to assist with the user query.
You are given a list of documents within XML tags:
{"doc_id": 1, "title": "History Document Title", "text": "From the early 12th century, French builders developed the Gothic style, marked by the use of rib vaults, pointed arches, flying buttresses, and large stained glass windows. It was used mainly in churches and cathedrals, and continued in use until the 16th century in much of Europe. Classic examples of Gothic architecture include Chartres Cathedral and Reims Cathedral in France as well as Salisbury Cathedral in England. Stained glass became a crucial element in the design of churches, which continued to use extensive wall-paintings, now almost all lost.", "source": ""}
{"doc_id": 2, "title": "Gothic Book", "text": "From long time ago, French builders developed the Gothic style, marked by the use of rib vaults, pointed arches, flying buttresses, and large stained glass windows. It was used mainly in churches and cathedrals, and continued in use until the 16th century in much of Europe. Classic examples of Gothic architecture include Chartres Cathedral and Reims Cathedral in France as well as Salisbury Cathedral in England. Stained glass became a crucial element in the design of churches, which continued to use extensive wall-paintings, now almost all lost.", "source": ""}
{"doc_id": 3, "title": "More Recent Book", "text": "From yesterday, French builders developed the Gothic style, marked by the use of rib vaults, pointed arches, flying buttresses, and large stained glass windows. It was used mainly in churches and cathedrals, and continued in use until the 16th century in much of Europe. Classic examples of Gothic architecture include Chartres Cathedral and Reims Cathedral in France as well as Salisbury Cathedral in England. Stained glass became a crucial element in the design of churches, which continued to use extensive wall-paintings, now almost all lost.", "source": ""}
Write the response to the user's input by strictly aligning with the facts in the provided documents. If the information needed to answer the question is not available in the documents, inform the user that the question cannot be answered based on the available data.<|end_of_text|>
```
* Granite 4.0 chat template also supports combining tool-use and RAG capabilities through an appropriately designed system prompt. Note that order matters, the chat template lists tools first followed by documents. Moreover, if a user-defined system prompt is provided, it will appear first, followed by the tools section and then the documents section.
```
<|start_of_role|>system<|end_of_role|>You are a weather assistant that responds with relevant function calls instead of natural language.
You are a helpful assistant with access to the following tools. You may call one or more tools to assist with the user query.
You are provided with function signatures within XML tags:
{"type": "function", "function": {"name": "get_current_weather", "description": "Get the current weather for a specified city.", "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "Name of the city"}}, "required": ["city"]}}}
{"type": "function", "function": {"name": "get_time", "description": "Get the current time for a specified location.", "parameters": {"type": "object", "properties": {"location": {"type": "string", "description": "Coordinates of the location"}}, "required": ["location"]}}}
For each tool call, return a json object with function name and arguments within XML tags:
{"name": , "arguments": }
. If a tool does not exist in the provided list of tools, notify the user that you do not have the ability to fulfill the request.
You are a helpful assistant with access to the following documents. You may use one or more documents to assist with the user query.
You are given a list of documents within XML tags:
{"doc_id": 1, "title": "", "text": "From the early 12th century, French builders developed the Gothic style, marked by the use of rib vaults, pointed arches, flying buttresses, and large stained glass windows. It was used mainly in churches and cathedrals, and continued in use until the 16th century in much of Europe. Classic examples of Gothic architecture include Chartres Cathedral and Reims Cathedral in France as well as Salisbury Cathedral in England. Stained glass became a crucial element in the design of churches, which continued to use extensive wall-paintings, now almost all lost.", "source": ""}
{"doc_id": 2, "title": "", "text": "From long time ago, French builders developed the Gothic style, marked by the use of rib vaults, pointed arches, flying buttresses, and large stained glass windows. It was used mainly in churches and cathedrals, and continued in use until the 16th century in much of Europe. Classic examples of Gothic architecture include Chartres Cathedral and Reims Cathedral in France as well as Salisbury Cathedral in England. Stained glass became a crucial element in the design of churches, which continued to use extensive wall-paintings, now almost all lost.", "source": ""}
{"doc_id": 3, "title": "", "text": "From yesterday, French builders developed the Gothic style, marked by the use of rib vaults, pointed arches, flying buttresses, and large stained glass windows. It was used mainly in churches and cathedrals, and continued in use until the 16th century in much of Europe. Classic examples of Gothic architecture include Chartres Cathedral and Reims Cathedral in France as well as Salisbury Cathedral in England. Stained glass became a crucial element in the design of churches, which continued to use extensive wall-paintings, now almost all lost.", "source": ""}
Write the response to the user's input by strictly aligning with the facts in the provided documents. If the information needed to answer the question is not available in the documents, inform the user that the question cannot be answered based on the available data.<|end_of_text|>
```
* About tool calling
* Granite 4.0 chat template automatically lists tools between `` and `` tags as part of the `system` message when a list of tools is provided.
* Granite 4.0 chat template automatically returns tool calls between `` and `` tags within the assistant turn. Example:
```
<|start_of_role|>assistant<|end_of_role|>
{"name": "get_current_weather", "arguments": {"city": "Bengaluru"}}
<|end_of_text|>
```
* Moreover, Granite 4.0 chat template converts `tool` role content into a `user` role in which tool responses appear between `` and `` tags. Example:
```
<|start_of_role|>user<|end_of_role|>
Bengaluru is sunny with a temperature of 30°C.
<|end_of_text|>
```
* About RAG
* The chat template lists documents as part of the `system` turn between `` and `` tags.
* About FIM
* The tags supported for fill-in-the-middle (FIM) code completion are: `<|fim_prefix|>`, `<|fim_middle|>`, and `<|fim_suffix|>`. Make sure to use the correct FIM tags when using Granite 4.0 models for FIM code completions.
- Granite 4.0 models chat template uses reverse iteration over messages to identify the last user query index.
- All outputs should be terminated with `<|end_of_text|>` to clearly segment messages.
### Basic chat template example
Below, we show a basic example of Granite 4.0 models chat template.
```
<|start_of_role|>user<|end_of_role|>What is the largest ocean on Earth?<|end_of_text|>
<|start_of_role|>assistant<|end_of_role|>The largest ocean on Earth is the Pacific Ocean. It covers an area of about 63.8 million square miles (165.25 million square kilometers), which is more than twice the size of the second-largest ocean, the Atlantic Ocean. The Pacific Ocean lies between the Americas to the east and Asia and Australia to the west.<|end_of_text|>
```
Use the following code example to reproduce this output.
```python theme={null}
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
device = "cuda"
model_path = "ibm-granite/granite-4.0-h-tiny"
tokenizer = AutoTokenizer.from_pretrained(model_path)
# drop device_map if running on CPU
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
model.eval()
# change input text as desired
chat = [
{ "role": "user", "content": "What is the largest ocean on Earth?"},
]
chat = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
# tokenize the text
input_tokens = tokenizer(chat, return_tensors="pt").to(device)
# generate output tokens
output = model.generate(**input_tokens,
max_new_tokens=150)
# decode output tokens into text
output = tokenizer.batch_decode(output)
print(output[0])
```
## Granite 4.0 inference examples
### Basic examples
In this section, we provide basic examples for a variety of inference tasks.
#### Summarization
This example demonstrates how to summarize an interview transcript.
```
<|start_of_role|>user<|end_of_role|>Summarize a fragment of an interview transcript. In this interview, an NBC reporter interviews Simone Biles about her participation in Paris 2024 Olympic games.
Your response should only include the answer. Do not provide any further explanation.
Speaker 1 (00:00):
Simone, congratulations.
Simone (00:02):
Thank you.
Speaker 1 (00:02):
The last several years have been all about our expectations, what we thought you would do, what we thought the team would do. What were your expectations coming here?
Simone (00:10):
My expectations or at least the team's expectation was to go out there and win gold for Team USA, and we did just that. And after that, my expectation was go to all-around, see if you can place top three, see what happens. And then after that, everything else was a cherry on top. So Vault, gold. Floor, silver. I'm not mad.
Speaker 1 (00:28):
Are you proud of yourself?
Simone (00:30):
Yes. I'm very proud of myself for how I held it together all of those competition days, all throughout those routines. It's very rigorous for however many days we compete in a row. So I'm very proud of my performances.
Speaker 1 (00:41):
And you've been all about self-care.
Simone (00:42):
Yes.
Speaker 1 (00:43):
Did it work?
Simone (00:44):
Yes. No, most definitely. I've been seeing my therapist a lot while I've been here in Paris, so I owe a lot to her.
Speaker 1 (00:53):
I don't mean to make you do my job, but if you had to write the headlines of these games telling your story, what would it be?
Simone (01:02):
I would say my success is defined by what I make it.
Speaker 1 (01:09):
I like that.
Simone (01:09):
Yeah.
Speaker 1 (01:10):
I like that. I might use that.
Simone (01:11):
Okay. Good.
Speaker 1 (01:13):
You also inspired a lot of people along the way. Have you ever sat back and really thought about what you have contributed to this sport?
Simone (01:22):
I think the impact that I've made, I definitely see, because I see all of those little girls cheering for me, supporting me on Instagram, on TikTok, all of the outlets. So I do understand the impact that I've made. But to fully understand the depth of it, I think it'll take one day whenever I retire, and then I look back at the career and everything that I've done to evolve the sport.
Speaker 1 (01:42):
I mean, we've seen celebrities in the stands. We've seen young gymnasts looking up at you. It's been quite a ride. I mean, it's a lot of pressure on you, I would think. How have you dealt with it?
Simone (01:53):
Yes. It's a lot of pressure, but pressure is privilege. So I'm just super excited to represent the United States every time I get the opportunity.
Speaker 1 (02:00):
There have been so many moments. One that struck me was watching three Black athletes together on the podium. When that was happening, did you recognize the significance of it?
Simone (02:11):
Oh, absolutely. And I don't think we got to recognize it enough because the award ceremony happened so fast. They're trying to break down the set and move in the next event that's going to be there. But we all recognized it and we were really excited about it.
Summary:<|end_of_text|>
<|start_of_role|>assistant<|end_of_role|>Simone Biles talks about her expectations for the Paris 2024 Olympics, her pride in her performances, and the impact of self-care on her mental health. She also discusses the significance of being a role model for young gymnasts and the recognition of her achievements in the sport.<|end_of_text|>
```
Use the following code example to reproduce this output.
```python theme={null}
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
device = "cuda"
model_path = "ibm-granite/granite-4.0-h-tiny"
tokenizer = AutoTokenizer.from_pretrained(model_path)
# drop device_map if running on CPU
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
model.eval()
interview_transcript = """Speaker 1 (00:00):
Simone, congratulations.
Simone (00:02):
Thank you.
Speaker 1 (00:02):
The last several years have been all about our expectations, what we thought you would do, what we thought the team would do. What were your expectations coming here?
Simone (00:10):
My expectations or at least the team's expectation was to go out there and win gold for Team USA, and we did just that. And after that, my expectation was go to all-around, see if you can place top three, see what happens. And then after that, everything else was a cherry on top. So Vault, gold. Floor, silver. I'm not mad.
Speaker 1 (00:28):
Are you proud of yourself?
Simone (00:30):
Yes. I'm very proud of myself for how I held it together all of those competition days, all throughout those routines. It's very rigorous for however many days we compete in a row. So I'm very proud of my performances.
Speaker 1 (00:41):
And you've been all about self-care.
Simone (00:42):
Yes.
Speaker 1 (00:43):
Did it work?
Simone (00:44):
Yes. No, most definitely. I've been seeing my therapist a lot while I've been here in Paris, so I owe a lot to her.
Speaker 1 (00:53):
I don't mean to make you do my job, but if you had to write the headlines of these games telling your story, what would it be?
Simone (01:02):
I would say my success is defined by what I make it.
Speaker 1 (01:09):
I like that.
Simone (01:09):
Yeah.
Speaker 1 (01:10):
I like that. I might use that.
Simone (01:11):
Okay. Good.
Speaker 1 (01:13):
You also inspired a lot of people along the way. Have you ever sat back and really thought about what you have contributed to this sport?
Simone (01:22):
I think the impact that I've made, I definitely see, because I see all of those little girls cheering for me, supporting me on Instagram, on TikTok, all of the outlets. So I do understand the impact that I've made. But to fully understand the depth of it, I think it'll take one day whenever I retire, and then I look back at the career and everything that I've done to evolve the sport.
Speaker 1 (01:42):
I mean, we've seen celebrities in the stands. We've seen young gymnasts looking up at you. It's been quite a ride. I mean, it's a lot of pressure on you, I would think. How have you dealt with it?
Simone (01:53):
Yes. It's a lot of pressure, but pressure is privilege. So I'm just super excited to represent the United States every time I get the opportunity.
Speaker 1 (02:00):
There have been so many moments. One that struck me was watching three Black athletes together on the podium. When that was happening, did you recognize the significance of it?
Simone (02:11):
Oh, absolutely. And I don't think we got to recognize it enough because the award ceremony happened so fast. They're trying to break down the set and move in the next event that's going to be there. But we all recognized it and we were really excited about it."""
chat=[
{"role": "user", "content": "Summarize a fragment of an interview transcript. In this interview, an NBC reporter interviews Simone Biles about her participation in Paris 2024 Olympic games.\nYour response should only include the answer. Do not provide any further explanation.\n"+interview_transcript+"\nSummary:"}
]
chat = tokenizer.apply_chat_template(chat,tokenize=False, add_generation_prompt=True)
# tokenize the text
input_tokens = tokenizer(chat, return_tensors="pt").to(device)
# generate output tokens
output = model.generate(**input_tokens,
max_new_tokens=200)
# decode output tokens into text
output = tokenizer.batch_decode(output)
# print output
print(output[0])
```
#### Text classification
This example demonstrates a classification task for movie reviews. The user query includes classification examples to improve the model's response accuracy.
```
<|start_of_role|>user<|end_of_role|>Classify the sentiment of the movie reviews as positive or negative.
Your response should only include the answer. Do not provide any further explanation.
Here are some examples, complete the last one:
Review:
Oh, where do I even begin? Barbie 2023 is a tour de force that has left me utterly captivated, enchanted, and spellbound. Every moment of this cinematic marvel was nothing short of pure excellence, deserving nothing less than a perfect 10 out of 10 rating!
Sentiment:
positive
Review:
It's a shame because I love Little Women and Lady Bird. Barbie did not serve. It's a long ramble about how matriarchy is perfect and patriarchy is stupid. I agree with the latter, but the execution is just awful. Mattel's CEO and corporate people started as a mockery of men having all the top positions in a company; as the movie goes, they're just there at the back of your mind, and it's an unpleasant experience because they did nothing after. There were so many unnecessary scenes that could have been meaningful. For example, what's the scene where Allan fights other Kens for? I'm also surprised that there were no gay Barbies and Kens. And I thought this was supposed to "break" gender norms. So many seeds were planted at once, but none reached their full potential.
Sentiment:
negative
Review:
Russell Crowe's new action movie Land of Bad can't break the star's recent streak of poor Rotten Tomatoes ratings. Co-starring Liam and Luke Hemsworth, Crowe's latest action effort concerns a special ops mission in the Philippines that goes wrong, leading to a harrowing fight for survival. Crowe plays Reaper, a drone pilot who must guide a group of outnumbered and stranded soldiers back to safety.
Despite the Land of Bad cast including big names like Crowe and two of the Hemsworths, the action film has failed to impress critics, currently sitting at 52% fresh on Rotten Tomatoes on 24 reviews, becoming the fifth straight Crowe-starring film to be certified rotten by the review aggregator.
Sentiment:<|end_of_text|>
<|start_of_role|>assistant<|end_of_role|>positive<|end_of_text|>
```
Use the following code example to reproduce this output.
```python theme={null}
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
device = "cuda"
model_path = "ibm-granite/granite-4.0-h-tiny"
tokenizer = AutoTokenizer.from_pretrained(model_path)
# drop device_map if running on CPU
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
model.eval()
prompt = """Classify the sentiment of the movie reviews as positive or negative.
Your response should only include the answer. Do not provide any further explanation.
Here are some examples, complete the last one:
Review:
Oh, where do I even begin? Barbie 2023 is a tour de force that has left me utterly captivated, enchanted, and spellbound. Every moment of this cinematic marvel was nothing short of pure excellence, deserving nothing less than a perfect 10 out of 10 rating!
Sentiment:
positive
Review:
It's a shame because I love Little Women and Lady Bird. Barbie did not serve. It's a long ramble about how matriarchy is perfect and patriarchy is stupid. I agree with the latter, but the execution is just awful. Mattel's CEO and corporate people started as a mockery of men having all the top positions in a company; as the movie goes, they're just there at the back of your mind, and it's an unpleasant experience because they did nothing after. There were so many unnecessary scenes that could have been meaningful. For example, what's the scene where Allan fights other Kens for? I'm also surprised that there were no gay Barbies and Kens. And I thought this was supposed to "break" gender norms. So many seeds were planted at once, but none reached their full potential.
Sentiment:
negative
Review:
Russell Crowe's new action movie Land of Bad can't break the star's recent streak of poor Rotten Tomatoes ratings. Co-starring Liam and Luke Hemsworth, Crowe's latest action effort concerns a special ops mission in the Philippines that goes wrong, leading to a harrowing fight for survival. Crowe plays Reaper, a drone pilot who must guide a group of outnumbered and stranded soldiers back to safety.
Despite the Land of Bad cast including big names like Crowe and two of the Hemsworths, the action film has failed to impress critics, currently sitting at 52% fresh on Rotten Tomatoes on 24 reviews, becoming the fifth straight Crowe-starring film to be certified rotten by the review aggregator.
Sentiment:"""
chat=[
{"role": "user", "content": prompt}
]
chat = tokenizer.apply_chat_template(chat,tokenize=False, add_generation_prompt=True)
# tokenize the text
input_tokens = tokenizer(chat, return_tensors="pt").to(device)
# generate output tokens
output = model.generate(**input_tokens,
max_new_tokens=200)
# decode output tokens into text
output = tokenizer.batch_decode(output)
# print output
print(output[0])
```
#### Text extraction
This example demonstrates how to extract certain information from a set of documents with a similar structural pattern.
```
<|start_of_role|>user<|end_of_role|>Extract the Line Of Credit Facility Maximum Borrowing Capacity from the 10K sentences.
Your response should only include the answer. Do not provide any further explanation.
Here are some examples, complete the last one:
10K Sentence:
The credit agreement also provides that up to $500 million in commitments may be used for letters of credit.
Line Of Credit Facility Maximum Borrowing Capacity:
$500M
10K Sentence:
In March 2020, we upsized the Credit Agreement by $100 million, which matures July 2023, to $2.525 billion.
Line Of Credit Facility Maximum Borrowing Capacity:
$2.525B
10K Sentence:
We prepared our impairment test as of October 1, 2022 and determined that the fair values of each of our reporting units exceeded net book value by more than 50%. Among our reporting units, the narrowest difference between the calculated fair value and net book value was in our Principal Markets segment's Canada reporting unit, whose calculated fair value exceeded its net book value by 53%. Future developments related to macroeconomic factors, including increases to the discount rate used, or changes to other inputs and assumptions, including revenue growth, could reduce the fair value of this and/or other reporting units and lead to impairment. There were no goodwill impairment losses recorded for the nine months ended December 31, 2022. Cumulatively, the Company has recorded $469 million in goodwill impairment charges within its former EMEA ($293 million) and current United States ($176 million) reporting units. Revolving Credit Agreement In October 2021, we entered into a $3.15 billion multi-currency revolving credit agreement (the "Revolving Credit Agreement") for our future liquidity needs. The Revolving Credit Agreement expires, unless extended, in October 2026. Interest rates on borrowings under the Revolving Credit Agreement are based on prevailing market interest rates, plus a margin, as further described in the Revolving Credit Agreement. The total expense recorded by the Company for the Revolving Credit Agreement was not material in any of the periods presented. We may voluntarily prepay borrowings under the Revolving Credit Agreement without premium or penalty, subject to customary "breakage" costs. The Revolving Credit Agreement includes certain customary mandatory prepayment provisions. Interest on Debt Interest expense for the three and nine months ended December 31, 2022 was $27 million and $65 million, compared to $18 million and $50 million for the three and nine months ended December 31, 2021. Most of the interest for the pre-Separation period presented in the historical Consolidated Income Statement reflects the allocation of interest expense associated with debt issued by IBM from which a portion of the proceeds benefited Kyndryl.
Line Of Credit Facility Maximum Borrowing Capacity:<|end_of_text|>
<|start_of_role|>assistant<|end_of_role|>$3.15B<|end_of_text|>
```
Use the following code example to reproduce this output.
```python theme={null}
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
device = "cuda"
model_path = "ibm-granite/granite-4.0-h-tiny"
tokenizer = AutoTokenizer.from_pretrained(model_path)
# drop device_map if running on CPU
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
model.eval()
prompt = """Extract the Line Of Credit Facility Maximum Borrowing Capacity from the 10K sentences.
Your response should only include the answer. Do not provide any further explanation.
Here are some examples, complete the last one:
10K Sentence:
The credit agreement also provides that up to $500 million in commitments may be used for letters of credit.
Line Of Credit Facility Maximum Borrowing Capacity:
$500M
10K Sentence:
In March 2020, we upsized the Credit Agreement by $100 million, which matures July 2023, to $2.525 billion.
Line Of Credit Facility Maximum Borrowing Capacity:
$2.525B
10K Sentence:
We prepared our impairment test as of October 1, 2022 and determined that the fair values of each of our reporting units exceeded net book value by more than 50%. Among our reporting units, the narrowest difference between the calculated fair value and net book value was in our Principal Markets segment's Canada reporting unit, whose calculated fair value exceeded its net book value by 53%. Future developments related to macroeconomic factors, including increases to the discount rate used, or changes to other inputs and assumptions, including revenue growth, could reduce the fair value of this and/or other reporting units and lead to impairment. There were no goodwill impairment losses recorded for the nine months ended December 31, 2022. Cumulatively, the Company has recorded $469 million in goodwill impairment charges within its former EMEA ($293 million) and current United States ($176 million) reporting units. Revolving Credit Agreement In October 2021, we entered into a $3.15 billion multi-currency revolving credit agreement (the "Revolving Credit Agreement") for our future liquidity needs. The Revolving Credit Agreement expires, unless extended, in October 2026. Interest rates on borrowings under the Revolving Credit Agreement are based on prevailing market interest rates, plus a margin, as further described in the Revolving Credit Agreement. The total expense recorded by the Company for the Revolving Credit Agreement was not material in any of the periods presented. We may voluntarily prepay borrowings under the Revolving Credit Agreement without premium or penalty, subject to customary "breakage" costs. The Revolving Credit Agreement includes certain customary mandatory prepayment provisions. Interest on Debt Interest expense for the three and nine months ended December 31, 2022 was $27 million and $65 million, compared to $18 million and $50 million for the three and nine months ended December 31, 2021. Most of the interest for the pre-Separation period presented in the historical Consolidated Income Statement reflects the allocation of interest expense associated with debt issued by IBM from which a portion of the proceeds benefited Kyndryl.
Line Of Credit Facility Maximum Borrowing Capacity:"""
chat=[
{"role": "user", "content": prompt}
]
chat = tokenizer.apply_chat_template(chat,tokenize=False, add_generation_prompt=True)
# tokenize the text
input_tokens = tokenizer(chat, return_tensors="pt").to(device)
# generate output tokens
output = model.generate(**input_tokens,
max_new_tokens=200)
# decode output tokens into text
output = tokenizer.batch_decode(output)
# print output
print(output[0])
```
#### Text translation
Granite 4.0 models also support tasks in multiple languages. This is a basic example of how to use the models to translate text from English to Spanish.
```
<|start_of_role|>user<|end_of_role|>Please translate the following list of greetings from English to Spanish.
Morning!, how are things?, hello, it's good to see you, what's up?
Please only output the translation, and nothing else.<|end_of_text|>
<|start_of_role|>assistant<|end_of_role|>Buenos días!
¿Cómo estás?
¡Hola!
¡Es buenísimo verte!
¿Qué tal?<|end_of_text|>
```
Use the following code example to reproduce this output.
```python theme={null}
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
device = "cuda"
model_path = "ibm-granite/granite-4.0-h-tiny"
tokenizer = AutoTokenizer.from_pretrained(model_path)
# drop device_map if running on CPU
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
model.eval()
prompt = """Please translate the following list of greetings from English to Spanish.
Morning!, how are things?, hello, it's good to see you, what's up?
Please only output the translation, and nothing else."""
chat=[
{"role": "user", "content": prompt}
]
chat = tokenizer.apply_chat_template(chat,tokenize=False, add_generation_prompt=True)
# tokenize the text
input_tokens = tokenizer(chat, return_tensors="pt").to(device)
# generate output tokens
output = model.generate(**input_tokens,
max_new_tokens=200)
# decode output tokens into text
output = tokenizer.batch_decode(output)
# print output
print(output[0])
```
Granite 4.0 models support text translation as well as other multilingual tasks in English, German, Spanish, French, Japanese, Portuguese, Arabic, Czech, Italian, Korean, Dutch, and Chinese (Simplified).
#### Temporal reasoning
This is an example of a basic temporal reasoning question.
```
<|start_of_role|>user<|end_of_role|>Alice went to the store two days before her birthday. If her birthday was on a Friday, what day did she go to the store?<|end_of_text|>
<|start_of_role|>assistant<|end_of_role|>If Alice's birthday was on a Friday and she went to the store two days before her birthday, then she went to the store on a Wednesday.<|end_of_text|>
```
Use the following code example to reproduce this output.
```python theme={null}
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
device = "cuda"
model_path = "ibm-granite/granite-4.0-h-tiny"
tokenizer = AutoTokenizer.from_pretrained(model_path)
# drop device_map if running on CPU
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
model.eval()
prompt = """Alice went to the store two days before her birthday. If her birthday was on a Friday, what day did she go to the store?"""
chat=[
{"role": "user", "content": prompt}
]
chat = tokenizer.apply_chat_template(chat,tokenize=False, add_generation_prompt=True)
# tokenize the text
input_tokens = tokenizer(chat, return_tensors="pt").to(device)
# generate output tokens
output = model.generate(**input_tokens,
max_new_tokens=200)
# decode output tokens into text
output = tokenizer.batch_decode(output)
# print output
print(output[0])
```
#### Logical reasoning
This is an example of a basic logical reasoning question.
```
<|start_of_role|>user<|end_of_role|>If both statements below are true:
If a person is a teacher, then they work at a school.
Maria does not work at a school.
What can we conclude about Maria?<|end_of_text|>
<|start_of_role|>assistant<|end_of_role|>We can conclude that Maria is not a teacher.
Here's the reasoning:
1. The first statement says that if a person is a teacher, then they work at a school. This can be written as: Teacher → Works at a school.
2. The second statement tells us that Maria does not work at a school. This can be written as: Not Works at a school.
3. Since the first statement establishes a conditional relationship between being a teacher and working at a school, we can use the contrapositive of this statement to draw a conclusion about Maria.
4. The contrapositive of "Teacher → Works at a school" is "Not Works at a school → Not a teacher."
5. Since Maria does not work at a school (Not Works at a school), we can conclude that Maria is not a teacher (Not a teacher).
Therefore, based on the given statements, we can conclude that Maria is not a teacher.<|end_of_text|>
```
Use the following code example to reproduce this output.
```python theme={null}
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
device = "cuda"
model_path = "ibm-granite/granite-4.0-h-tiny"
tokenizer = AutoTokenizer.from_pretrained(model_path)
# drop device_map if running on CPU
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
model.eval()
prompt = """If both statements below are true:
If a person is a teacher, then they work at a school.
Maria does not work at a school.
What can we conclude about Maria?"""
chat=[
{"role": "user", "content": prompt}
]
chat = tokenizer.apply_chat_template(chat,tokenize=False, add_generation_prompt=True)
# tokenize the text
input_tokens = tokenizer(chat, return_tensors="pt").to(device)
# generate output tokens
output = model.generate(**input_tokens,
max_new_tokens=200)
# decode output tokens into text
output = tokenizer.batch_decode(output)
# print output
print(output[0])
```
### Building prompts with transformers library
The `apply_chat_template` function from the transformers library automatically applies the basic chat template structure of Granite 4.0 models to your prompts. To build prompts that integrate advanced features via the `apply_chat_template` you must use the appropriate `kwargs`.
* Use `tools` to provide the list of tools in tool-calling tasks. This automatically activates the tool-calling system prompt and formats the tool list.
* Use `documents` to provide the list of documents for RAG prompts. This automatically activates the RAG system prompt and formats the document list.
We strongly recommend that developers use the `apply_chat_template` function to construct their prompts, as it enhances the development experience and minimizes the risk of inference errors caused by manually crafting chat templates in `Jinja`. However, you can also load a chat template that incorporates Granite 4.0's advanced features without using the `apply_chat_template` function.
In the following example, we load the template for RAG inference. Note that the final model prompt is saved in `input_text` variable. You can take this example as baseline to build wrappers for libraries that do no support `kwargs`.
```python theme={null}
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
device = "cuda"
model_path = "ibm-granite/granite-4.0-h-tiny"
tokenizer = AutoTokenizer.from_pretrained(model_path)
# drop device_map if running on CPU
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
model.eval()
input_text = '''<|start_of_role|>system<|end_of_role|>You are a helpful assistant with access to the following documents. You may use one or more documents to assist with the user query.
You are given a list of documents within XML tags:
{"doc_id": 1, "title": "History Document Title", "text": "From the early 12th century, French builders developed the Gothic style, marked by the use of rib vaults, pointed arches, flying buttresses, and large stained glass windows. It was used mainly in churches and cathedrals, and continued in use until the 16th century in much of Europe. Classic examples of Gothic architecture include Chartres Cathedral and Reims Cathedral in France as well as Salisbury Cathedral in England. Stained glass became a crucial element in the design of churches, which continued to use extensive wall-paintings, now almost all lost.", "source": ""}
{"doc_id": 2, "title": "Gothic Book", "text": "From long time ago, French builders developed the Gothic style, marked by the use of rib vaults, pointed arches, flying buttresses, and large stained glass windows. It was used mainly in churches and cathedrals, and continued in use until the 16th century in much of Europe. Classic examples of Gothic architecture include Chartres Cathedral and Reims Cathedral in France as well as Salisbury Cathedral in England. Stained glass became a crucial element in the design of churches, which continued to use extensive wall-paintings, now almost all lost.", "source": ""}
{"doc_id": 3, "title": "More Recent Book", "text": "From yesterday, French builders developed the Gothic style, marked by the use of rib vaults, pointed arches, flying buttresses, and large stained glass windows. It was used mainly in churches and cathedrals, and continued in use until the 16th century in much of Europe. Classic examples of Gothic architecture include Chartres Cathedral and Reims Cathedral in France as well as Salisbury Cathedral in England. Stained glass became a crucial element in the design of churches, which continued to use extensive wall-paintings, now almost all lost.", "source": ""}
Write the response to the user's input by strictly aligning with the facts in the provided documents. If the information needed to answer the question is not available in the documents, inform the user that the question cannot be answered based on the available data.<|end_of_text|>
<|start_of_role|>user<|end_of_role|>Who developed the Gothic architectural style?<|end_of_text|>
<|start_of_role|>assistant<|end_of_role|>'''
inputs = tokenizer(input_text, return_tensors="pt")
output = model.generate(inputs["input_ids"].to(device), attention_mask=inputs["attention_mask"].to(device), max_new_tokens=500)
answer = tokenizer.decode(output[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
print(answer)
```
The execution of this script returns the assistant's output below:
```
French builders developed the Gothic architectural style from the early 12th century.
```
### Inference Tips
* Verify the Max New Tokens setting. If you see a model response stopping mid-sentence, the max new tokens setting is likely set too low. This is particularly critical in long-context tasks.
* Avoid pronouns in follow-up questions. For example, do not use "Can you edit it?", instead use "Can you edit the table?".
* Reduce explanation length. If the explanations provided by the model are too long, update the instruction to make it clear there should be no additional explanations.
* Fix run-on sentences/responses. If the model is generating run-on sentences/responses, try reducing the max tokens output parameter or adding line breaks or spaces as stop token(s). This should lead the model to stop generating the output after generating these tokens.
* For prompts that include in-context examples, consider using the example labels as a stop token so the model stops generation after providing the answer.
# Risk Detection
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/risk-detection
Use Granite Guardian to screen user prompts and LLM responses for harmful content.
Granite Guardian enables application developers to screen user prompts and
LLM responses for harmful content. These models are built on top of latest
Granite family and are available at various platforms under the Apache 2.0
license. This recipe gets you quickly up and running with AI risk detection.
You will need the following credentials to run this recipe in Colab:
* Hugging Face token
* watsonx API Key
* watsonx Project ID
* watsonx url
Instructions for obtaining these credentials can be found [here](/granite/docs/use-cases/getting-credentials).
Granite Guardian examples may contain offensive language, stereotypes, or
discriminatory content.
Explore sample code in a GitHub repo
Execute sample code in Colab
# Document Summarization
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/summarize
Summarize a long document using a Granite model.
This recipe shows how to summarize a long document using Granite. The document used in the recipe is H.D. Thoreau's "Walden" from Project Gutenberg.
You will need a Replicate API token to run this recipe in Colab. Instructions for obtaining this credential can be found [here](/granite/docs/use-cases/getting-credentials).
Explore sample code in a GitHub repo
Execute sample code in Colab
# Text to Python
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/text-to-python
Use Granite to generate Python code from text prompts.
This recipe demonstrates how to use Granite to generate Python code from text prompts.
You will need a Replicate API token and a Hugging Face token to run this recipe in Colab. Instructions for obtaining these credentials can be found [here](/granite/docs/use-cases/getting-credentials).
Explore sample code in a GitHub repo
Execute sample code in Colab
# Text to Shell Script
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/text-to-shell
Generate and run Bash scripts from natural language.
This recipe sets up a text-to-shell-script utility using Granite Code and Ollama. You will be able to generate and run Bash scripts
using simple, human-readable language.
You will need a Replicate API token to run this recipe in Colab. Instructions for obtaining this credential can be found [here](/granite/docs/use-cases/getting-credentials).
Explore sample code in a GitHub repo
Execute sample code in Colab
# Travel Planner
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/travel-planner
Create a travel planner agent that can answer complex queries about planning a trip.
This recipe create a travel planner agent with LangChain agents using a Granite model running on watsonx.ai that can answer complex queries about planning a trip.
You will need the following credentials to run this recipe in Colab:
* watsonx API Key
* watsonx Project ID
* watsonx url
Instructions for obtaining these credentials can be found [here](/granite/docs/use-cases/getting-credentials).
Explore sample code in a GitHub repo
Execute sample code in Colab
# Unitxt
Source: https://wwwpoc.ibm.com/granite/docs/use-cases/unitxt
Evaluate Granite's performance.
[Unitxt](https://www.unitxt.ai/en/latest/) is an innovative library for textual data preparation and evaluation of generative language models. It deconstructs the data preparation and evaluation flows into modular components, enabling easy customization and sharing between practitioners. Unitxt as an extensive catalog of datasets, tasks, templates, metrics and textual operators, that can be used as-is, or be combined in innovative ways to create new evaluations.
In this recipe we evaluate Granite's performance on the OpenbookQA dataset from HuggingFace. We load the dataset, generate the model client, run inference, and evaluate the results.
You will need a Hugging Face token to run this recipe in Colab. Instructions for obtaining this credential can be found [here](/granite/docs/use-cases/getting-credentials).
Explore sample code in a GitHub repo
Execute sample code in Colab