Views
No views yet
1pip install torch torchvision torchaudio
2pip install accelerate
3pip install transformers1from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig
2import torch
3
4# Model and tokenizer
5model_name = "ruslanmv/granite-3.1-2b-Reasoning"
6tokenizer = AutoTokenizer.from_pretrained(model_name)
7model = AutoModelForCausalLM.from_pretrained(
8 model_name,
9 device_map='auto', # or 'cuda' if you have only one GPU
10 torch_dtype=torch.float16, # Use float16 for faster and less memory intensive inference
11 load_in_4bit=True # Enable 4-bit quantization for lower memory usage - requires bitsandbytes
12)
13
14# Prepare dataset
15SYSTEM_PROMPT = """
16Respond in the following format:
17<reasoning>
18...
19</reasoning>
20<answer>
21...
22</answer>
23"""
24text = tokenizer.apply_chat_template([
25 {"role" : "system", "content" : SYSTEM_PROMPT},
26 {"role" : "user", "content" : "Calculate pi."},
27], tokenize = False, add_generation_prompt = True)
28
29inputs = tokenizer(text, return_tensors="pt").to("cuda") # Move input tensor to GPU
30
31# Sampling parameters
32generation_config = GenerationConfig(
33 temperature = 0.8,
34 top_p = 0.95,
35 max_new_tokens = 1024, # Equivalent to max_tokens in the original code, but for generation
36)
37
38# Inference
39with torch.inference_mode(): # Use inference mode for faster generation
40 outputs = model.generate(**inputs, generation_config=generation_config)
41
42output = tokenizer.decode(outputs[0], skip_special_tokens=True)
43
44# Find the start of the actual response
45start_index = output.find("assistant")
46if start_index != -1:
47 # Remove the initial part including "assistant"
48 output = output[start_index + len("assistant"):].strip()
49
50print(output)<reasoning>
Pi is an irrational number, which means it cannot be precisely calculated using finite decimal or fractional notation. It is typically represented by the Greek letter π and its approximate value is 3.14159. However, for a more precise calculation, we can use mathematical algorithms like the Leibniz formula for π or the Gregory-Leibniz series.
The Leibniz formula for π is:
π = 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 - 1/15 +...)
This series converges slowly, so many terms are needed for a good approximation. For instance, using 10 terms, the approximation would be:
π ≈ 4 * (1 - 0.3333333333333333 + 0.1111111111111111 - 0.0344827586206897 + 0.0090040875518672 - 0.0025958422650073 + 0.0006929403729561 - 0.0001866279043531 + 0.0000499753694946 - 0.0000133386323746 + 0.0000035303398593 - 0.0000009009433996)
π ≈ 3.141592653589793
This is a rough approximation of π using 10 terms. For a more precise value, you can use more terms or employ other algorithms.
</reasoning>
<answer>
π ≈ 3.141592653589793
</answer>@misc{ruslanmv2025granite,
title={Fine-Tuning Granite-3.1 for Advanced Reasoning},
author={Ruslan M.V.},
year={2025},
url={https://huggingface.co/ruslanmv/granite-3.1-2b-Reasoning}
}