This repository contains ONNX versions of the Granite Guardian HAP 38M model, including onnx and quantized onnx variants. The models are optimized for efficient inference in production environments.
-
Onnx Model (guardian_model.onnx):
- Full precision FP32 model
- Best for scenarios requiring maximum accuracy
-
Quantized Model (guardian_model_quantized.onnx):
- INT8 quantized model
- Optimized for faster inference and smaller size
- Maintains comparable accuracy to the original model
1<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.17.0" />
2<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
1using Microsoft.ML.OnnxRuntime;
2using Microsoft.ML.OnnxRuntime.Tensors;
3using System.Net.Http;
4using Newtonsoft.Json;
5
6public class GuardianModel
7{
8 private readonly InferenceSession _session;
9 private readonly Dictionary<string, int> _tokenizer;
10
11 public GuardianModel(string modelPath, string tokenizerPath)
12 {
13 // Initialize ONNX session
14 _session = new InferenceSession(modelPath);
15
16 // Load tokenizer vocabulary
17 using var client = new HttpClient();
18 var vocab = client.GetStringAsync(tokenizerPath).Result;
19 _tokenizer = JsonConvert.DeserializeObject<Dictionary<string, int>>(vocab);
20 }
21
22 private int[] TokenizeText(string text)
23 {
24 var words = text.ToLower().Split(' ');
25 var tokens = new List<int>();
26
27 // Add start token
28 if (_tokenizer.ContainsKey("<s>"))
29 tokens.Add(_tokenizer["<s>"]);
30
31 // Tokenize words
32 foreach (var word in words)
33 {
34 if (_tokenizer.ContainsKey(word))
35 tokens.Add(_tokenizer[word]);
36 else
37 tokens.Add(_tokenizer["<unk>"]);
38 }
39
40 // Add end token
41 if (_tokenizer.ContainsKey("</s>"))
42 tokens.Add(_tokenizer["</s>"]);
43
44 // Pad sequence
45 while (tokens.Count < 128)
46 tokens.Add(_tokenizer["<pad>"]);
47 if (tokens.Count > 128)
48 tokens = tokens.Take(128).ToList();
49
50 return tokens.ToArray();
51 }
52
53 public (int Prediction, float Confidence) Predict(string text)
54 {
55 // Tokenize input
56 var tokens = TokenizeText(text);
57
58 // Create input tensor
59 var inputDims = new[] { 1, tokens.Length };
60 var inputTensor = new DenseTensor<long>(inputDims);
61 var attentionMask = new DenseTensor<long>(inputDims);
62
63 for (int i = 0; i < tokens.Length; i++)
64 {
65 inputTensor[0, i] = tokens[i];
66 attentionMask[0, i] = tokens[i] == _tokenizer["<pad>"] ? 0 : 1;
67 }
68
69 // Create input data
70 var inputs = new List<NamedOnnxValue>
71 {
72 NamedOnnxValue.CreateFromTensor("input_ids", inputTensor),
73 NamedOnnxValue.CreateFromTensor("attention_mask", attentionMask)
74 };
75
76 // Run inference
77 using var outputs = _session.Run(inputs);
78 var results = outputs.First().AsTensor<float>();
79
80 // Get prediction and confidence
81 var prediction = results.ToArray()
82 .Select((value, index) => new { Value = value, Index = index })
83 .OrderByDescending(x => x.Value)
84 .First();
85
86 return (prediction.Index, prediction.Value);
87 }
88}
89
90// Example usage
91var model = new GuardianModel(
92 "path/to/guardian_model.onnx",
93 "https://huggingface.co/KantiArumilli/granite-guardian-hap-38m-onnx/raw/main/tokenizer/vocab.json"
94);
95
96var (prediction, confidence) = model.Predict("Your text here");
97Console.WriteLine($"Prediction: {prediction}, Confidence: {confidence:F4}");
1import numpy as np
2import onnxruntime as ort
3from transformers import PreTrainedTokenizerFast
4from huggingface_hub import hf_hub_download
5
6def load_model(model_path, use_gpu=False):
7 providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if use_gpu else ['CPUExecutionProvider']
8 return ort.InferenceSession(model_path, providers=providers)
9
10def load_tokenizer(model_id):
11 # Download tokenizer files
12 tokenizer_file = hf_hub_download(
13 repo_id=model_id,
14 filename="tokenizer/tokenizer.json"
15 )
16
17 # Initialize tokenizer with special tokens
18 tokenizer = PreTrainedTokenizerFast(
19 tokenizer_file=tokenizer_file,
20 padding_side="right",
21 truncation_side="right"
22 )
23
24 # Set special tokens
25 special_tokens = {
26 "pad_token": "<pad>",
27 "eos_token": "</s>",
28 "bos_token": "<s>",
29 "unk_token": "<unk>"
30 }
31 tokenizer.add_special_tokens(special_tokens)
32
33 return tokenizer
34
35def predict(text, model, tokenizer):
36 # Tokenize input
37 inputs = tokenizer(
38 text,
39 padding=True,
40 truncation=True,
41 max_length=128,
42 return_tensors="np"
43 )
44
45 # Run inference
46 onnx_inputs = {
47 "input_ids": inputs["input_ids"],
48 "attention_mask": inputs["attention_mask"]
49 }
50 outputs = model.run(None, onnx_inputs)
51
52 # Process output
53 logits = outputs[0]
54 prediction = np.argmax(logits, axis=1)[0]
55 confidence = float(np.max(logits, axis=1)[0])
56
57 return prediction, confidence
58
59# Example usage
60model_id = "KantiArumilli/granite-guardian-hap-38m-onnx"
61model_file = "guardian_model.onnx" # or "guardian_model_quantized.onnx"
62
63# Download model
64model_path = hf_hub_download(repo_id=model_id, filename=model_file)
65
66# Initialize model and tokenizer
67model = load_model(model_path)
68tokenizer = load_tokenizer(model_id)
69
70# Make prediction
71text = "Your text here"
72prediction, confidence = predict(text, model, tokenizer)
73print(f"Prediction: {prediction}, Confidence: {confidence:.4f}")
Presented by Mr. Kanti Arumilli
Founder & CEO
ALight Technology And Services Limited
and
ALight Technologies USA Inc.