> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-hi/gpu-devops/onnx-runtime.md).

# ONNX Runtime GPU

> **क्रॉस-प्लेटफ़ॉर्म, हार्डवेयर-त्वरित ML इन्फ़रेंस — किसी भी फ्रेमवर्क से कोई भी मॉडल तैनात करें**

ONNX Runtime (ORT) ONNX (Open Neural Network Exchange) मॉडलों के लिए Microsoft का ओपन-सोर्स इन्फ़रेंस इंजन है। यह एकीकृत API के माध्यम से CPUs, GPUs, और विशेष एक्सेलेरेटर पर हार्डवेयर-त्वरित इन्फ़रेंस प्रदान करता है। चाहे आपका मॉडल PyTorch, TensorFlow, Scikit-learn, या XGBoost में प्रशिक्षित हुआ हो — यदि आप उसे ONNX प्रारूप में निर्यात कर सकते हैं, तो ORT उसे अधिक तेज़ी से चला सकता है।

**GitHub:** [microsoft/onnxruntime](https://github.com/microsoft/onnxruntime) — 14K+ ⭐

***

## ONNX Runtime क्यों?

| विशेषता              | ONNX Runtime      | TorchScript    | TensorFlow Serving |
| -------------------- | ----------------- | -------------- | ------------------ |
| फ्रेमवर्क-स्वतंत्र   | ✅                 | ❌ केवल PyTorch | ❌ केवल TF          |
| GPU त्वरण            | ✅ CUDA/TensorRT   | ✅              | ✅                  |
| INT8/FP16 परिमाणीकरण | ✅                 | आंशिक          | आंशिक              |
| मोबाइल/एज परिनियोजन  | ✅                 | सीमित          | सीमित              |
| ऑपरेटर फ्यूज़न       | ✅                 | आंशिक          | ✅                  |
| आसान एकीकरण          | ✅ Python/C++/Java | Python         | Python/gRPC        |

{% hint style="success" %}
**मुख्य लाभ:** CUDA निष्पादन प्रदाता के साथ ONNX Runtime आमतौर पर प्रदान करता है **1.5–3x गति वृद्धि** कंप्यूटर विज़न और NLP मॉडलों के लिए मूल PyTorch इन्फ़रेंस की तुलना में।
{% endhint %}

***

## समर्थित निष्पादन प्रदाता

ONNX Runtime कई हार्डवेयर बैकएंड (निष्पादन प्रदाता) का समर्थन करता है:

| प्रदाता                     | हार्डवेयर     | उपयोग-प्रकरण          |
| --------------------------- | ------------- | --------------------- |
| `CUDAExecutionProvider`     | NVIDIA GPUs   | सामान्य GPU इन्फ़रेंस |
| `TensorrtExecutionProvider` | NVIDIA GPUs   | अधिकतम थ्रूपुट        |
| `CPUExecutionProvider`      | CPU           | फ़ॉलबैक / एज          |
| `ROCMExecutionProvider`     | AMD GPUs      | AMD हार्डवेयर         |
| `CoreMLExecutionProvider`   | Apple Silicon | macOS/iOS             |
| `OpenVINOExecutionProvider` | Intel         | Intel CPUs/GPUs       |

***

## पूर्वापेक्षाएँ

* GPU किराये वाले Clore.ai खाते
* Python का बुनियादी ज्ञान
* एक प्रशिक्षित मॉडल (PyTorch, TensorFlow, या पहले से निर्यातित ONNX)

***

## चरण 1 — Clore.ai पर GPU किराए पर लें

1. पर जाएँ [clore.ai](https://clore.ai) → **मार्केटप्लेस**
2. कोई भी NVIDIA GPU काम करेगा — छोटे मॉडलों के लिए RTX 3070 से लेकर बड़े ट्रांसफॉर्मर्स के लिए A100 तक
3. **ट्रांसफॉर्मर मॉडलों के लिए:** RTX 4090 या A100 अनुशंसित
4. **कंप्यूटर विज़न के लिए:** RTX 3090 या RTX 4090 पर्याप्त है

***

## चरण 2 — अपना कंटेनर तैनात करें

ONNX Runtime का कोई आधिकारिक पूर्व-निर्मित कंटेनर नहीं है, लेकिन NVIDIA CUDA बेस आदर्श है:

**Docker इमेज:**

```
nvcr.io/nvidia/cuda:12.8.1-cudnn-devel-ubuntu22.04
```

**पोर्ट:**

```
22
```

**Environment Variables:**

```
NVIDIA_VISIBLE_DEVICES=all
NVIDIA_DRIVER_CAPABILITIES=compute,utility
```

{% hint style="info" %}
वैकल्पिक रूप से, उपयोग करें `pytorch/pytorch:2.11.0-cuda12.8-cudnn9-runtime` जिसमें CUDA और ORT इंस्टॉलेशन के लिए तैयार Python परिवेश शामिल है।
{% endhint %}

***

## चरण 3 — GPU समर्थन के साथ ONNX Runtime इंस्टॉल करें

```bash
ssh root@<server-ip> -p <ssh-port>

# पैकेज अपडेट करें
apt-get update && apt-get install -y \\
    python3-pip \\
    python3-dev \\
    wget \\
    git \\
    libgomp1

# CUDA समर्थन के साथ ONNX Runtime इंस्टॉल करें
pip install onnxruntime-gpu

# सहायक पैकेज इंस्टॉल करें
pip install \\
    onnx \\
    numpy \\
    Pillow \\
    transformers \\
    torch \\
    torchvision \\
    fastapi \\
    uvicorn

# इंस्टॉलेशन सत्यापित करें
python3 << 'EOF'
import onnxruntime as ort
print(f"ORT संस्करण: {ort.__version__}")
print(f"उपलब्ध प्रदाता: {ort.get_available_providers()}")
# इसमें शामिल होना चाहिए: CUDAExecutionProvider, TensorrtExecutionProvider, CPUExecutionProvider
EOF
```

***

## चरण 4 — अपने मॉडल को ONNX में निर्यात करें

### PyTorch मॉडल निर्यात

```python
import torch
import torch.nn as nn
import onnx

# उदाहरण: ResNet50 निर्यात करें
model = torch.hub.load('pytorch/vision:v0.10.0', 'resnet50', pretrained=True)
model.eval()

# डमी इनपुट बनाएं (batch=1, RGB छवि 224x224)
dummy_input = torch.randn(1, 3, 224, 224)

# ONNX में निर्यात करें
torch.onnx.export(
    model,
    dummy_input,
    "resnet50.onnx",
    export_params=True,
    opset_version=17,              # नवीनतम स्थिर opset का उपयोग करें
    do_constant_folding=True,      # स्थिर ops को अनुकूलित करें
    input_names=["input"],
    output_names=["output"],
    dynamic_axes={
        "input": {0: "batch_size"},    # डायनामिक बैच
        "output": {0: "batch_size"}
    }
)
print("मॉडल सफलतापूर्वक निर्यात किया गया!")

# निर्यातित मॉडल को सत्यापित करें
onnx_model = onnx.load("resnet50.onnx")
onnx.checker.check_model(onnx_model)
print("ONNX मॉडल मान्य है!")
```

### HuggingFace Transformers निर्यात

```bash
# HuggingFace ONNX निर्यात के लिए optimum इंस्टॉल करें
pip install optimum[exporters]

# टेक्स्ट वर्गीकरण के लिए BERT निर्यात करें
optimum-cli export onnx \\
    --model bert-base-uncased \\
    --task text-classification \\
    ./bert_onnx/

# अनुकूलन के साथ निर्यात करें
optimum-cli export onnx \\
    --model microsoft/phi-2 \\
    --task text-generation \\
    --optimize O2 \\
    ./phi2_onnx/
```

### ORT अनुकूलन के साथ निर्यात

```python
from optimum.onnxruntime import ORTModelForSequenceClassification
from optimum.onnxruntime.configuration import OptimizationConfig, ORTConfig
from optimum.onnxruntime import ORTOptimizer

# लोड करें और अनुकूलित करें
model = ORTModelForSequenceClassification.from_pretrained(
    "distilbert-base-uncased-finetuned-sst-2-english",
    export=True
)

optimizer = ORTOptimizer.from_pretrained(model)
optimization_config = OptimizationConfig(
    optimization_level=2,
    optimize_for_gpu=True,
    fp16=True
)

optimizer.optimize(
    save_dir="./distilbert_optimized",
    optimization_config=optimization_config
)
```

***

## चरण 5 — ONNX Runtime के साथ इन्फ़रेंस चलाएँ

### बुनियादी GPU इन्फ़रेंस

```python
import onnxruntime as ort
import numpy as np
from PIL import Image
import torchvision.transforms as transforms

# GPU निष्पादन प्रदाताओं के साथ सेशन कॉन्फ़िगर करें
# प्रदाताओं को क्रम में आज़माया जाता है — पहले CUDA, फिर CPU फ़ॉलबैक
providers = [
    ("CUDAExecutionProvider", {
        "device_id": 0,
        "arena_extend_strategy": "kNextPowerOfTwo",
        "gpu_mem_limit": 4 * 1024 * 1024 * 1024,  # 4GB सीमा
        "cudnn_conv_algo_search": "EXHAUSTIVE",
        "do_copy_in_default_stream": True,
    }),
    "CPUExecutionProvider"
]

# प्रदर्शन के लिए सेशन विकल्प
opts = ort.SessionOptions()
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
opts.intra_op_num_threads = 8
opts.execution_mode = ort.ExecutionMode.ORT_PARALLEL

# मॉडल लोड करें
session = ort.InferenceSession(
    "resnet50.onnx",
    sess_options=opts,
    providers=providers
)

print(f"इस पर चल रहा है: {session.get_providers()}")

# इनपुट तैयार करें
transform = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

img = Image.open("test_image.jpg").convert("RGB")
img_tensor = transform(img).unsqueeze(0).numpy()

# इन्फ़रेंस चलाएँ
outputs = session.run(None, {"input": img_tensor})
probabilities = outputs[0][0]
top5_idx = probabilities.argsort()[-5:][::-1]
print("शीर्ष 5 पूर्वानुमान:", top5_idx, probabilities[top5_idx])
```

### थ्रूपुट के लिए बैच इन्फ़रेंस

```python
import onnxruntime as ort
import numpy as np
import time

session = ort.InferenceSession(
    "resnet50.onnx",
    providers=["CUDAExecutionProvider"]
)

# GPU को वार्म अप करें
dummy = np.random.randn(1, 3, 224, 224).astype(np.float32)
for _ in range(10):
    session.run(None, {"input": dummy})

# बैच आकारों का बेंचमार्क करें
for batch_size in [1, 4, 8, 16, 32, 64]:
    inputs = np.random.randn(batch_size, 3, 224, 224).astype(np.float32)
    
    start = time.time()
    n_iter = 100
    for _ in range(n_iter):
        session.run(None, {"input": inputs})
    elapsed = time.time() - start
    
    throughput = (batch_size * n_iter) / elapsed
    latency = (elapsed / n_iter) * 1000  # ms
    
    print(f"बैच {batch_size:3d}: {throughput:7.1f} छवि/सेक, {latency:.1f}ms/बैच")
```

***

## चरण 6 — TensorRT निष्पादन प्रदाता (अधिकतम प्रदर्शन)

NVIDIA GPUs के लिए, TensorRT EP और भी बेहतर प्रदर्शन देता है:

```python
import onnxruntime as ort
import numpy as np

# TensorRT निष्पादन प्रदाता कॉन्फ़िगरेशन
tensorrt_provider_options = {
    "trt_max_workspace_size": 4 * 1024 * 1024 * 1024,  # 4GB
    "trt_fp16_enable": True,          # तेज़ इन्फ़रेंस के लिए FP16 सक्षम करें
    "trt_int8_enable": False,
    "trt_engine_cache_enable": True,   # संकलित इंजनों को कैश करें
    "trt_engine_cache_path": "/tmp/trt_cache",
    "trt_max_partition_iterations": 1000,
    "trt_min_subgraph_size": 1,
    "trt_timing_cache_enable": True,
}

providers = [
    ("TensorrtExecutionProvider", tensorrt_provider_options),
    ("CUDAExecutionProvider", {"device_id": 0}),
    "CPUExecutionProvider"
]

session = ort.InferenceSession("resnet50.onnx", providers=providers)
print("सक्रिय प्रदाता:", session.get_providers()[0])

# पहली रन TensorRT इंजन को संकलित करती है (1-3 मिनट लग सकते हैं)
# बाद की रन कैश किए गए इंजन का उपयोग करती हैं और बहुत तेज़ होती हैं
```

{% hint style="warning" %}
**TensorRT इंजन संकलन** पहली इन्फ़रेंस पर होता है और इसमें 1–5 मिनट लग सकते हैं। कैशिंग सक्षम करें (`trt_engine_cache_enable: True`) ताकि संकलित इंजन सेशनों के बीच पुन: उपयोग हो सके।
{% endhint %}

***

## चरण 7 — अधिकतम गति के लिए INT8 परिमाणीकरण

```python
from onnxruntime.quantization import quantize_dynamic, quantize_static, QuantType
import onnxruntime as ort
import numpy as np

# डायनामिक INT8 परिमाणीकरण (कैलिब्रेशन डेटा की आवश्यकता नहीं)
quantize_dynamic(
    model_input="resnet50.onnx",
    model_output="resnet50_int8_dynamic.onnx",
    weight_type=QuantType.QInt8
)

# स्थिर INT8 परिमाणीकरण (कैलिब्रेशन डेटा आवश्यक है)
from onnxruntime.quantization import CalibrationDataReader

class ImageCalibrationReader(CalibrationDataReader):
    def __init__(self, data_dir, input_name="input"):
        self.data_dir = data_dir
        self.input_name = input_name
        self.images = self._load_images()
        self.idx = 0
    
    def _load_images(self):
        # 100 कैलिब्रेशन छवियाँ लोड करें
        import glob, torchvision.transforms as T
        from PIL import Image
        transform = T.Compose([T.Resize(256), T.CenterCrop(224), T.ToTensor()])
        images = []
        for path in glob.glob(f"{self.data_dir}/*.jpg")[:100]:
            img = Image.open(path).convert("RGB")
            images.append(transform(img).numpy())
        return images
    
    def get_next(self):
        if self.idx >= len(self.images):
            return None
        data = {self.input_name: self.images[self.idx:self.idx+1]}
        self.idx += 1
        return data

from onnxruntime.quantization import quantize_static, QuantFormat
quantize_static(
    model_input="resnet50.onnx",
    model_output="resnet50_int8_static.onnx",
    calibration_data_reader=ImageCalibrationReader("/data/calibration_images"),
    quant_format=QuantFormat.QDQ,
    weight_type=QuantType.QInt8
)
```

***

## चरण 8 — एक इन्फ़रेंस API बनाएं

```bash
cat > /workspace/onnx_api.py << 'EOF'
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse
import onnxruntime as ort
import numpy as np
from PIL import Image
import io
import torchvision.transforms as transforms
import json

app = FastAPI(title="ONNX Runtime इन्फ़रेंस API")

# स्टार्टअप पर मॉडल लोड करें
session = ort.InferenceSession(
    "resnet50.onnx",
    providers=["CUDAExecutionProvider", "CPUExecutionProvider"]
)

# ImageNet वर्ग लेबल लोड करें
with open("imagenet_classes.json") as f:
    classes = json.load(f)

transform = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

@app.get("/health")
async def health():
    return {"status": "ok", "providers": session.get_providers()}

@app.post("/predict")
async def predict(file: UploadFile = File(...), topk: int = 5):
    image_data = await file.read()
    img = Image.open(io.BytesIO(image_data)).convert("RGB")
    tensor = transform(img).unsqueeze(0).numpy()
    
    outputs = session.run(None, {"input": tensor})[0][0]
    top_indices = outputs.argsort()[-topk:][::-1]
    
    results = [
        {"label": classes[str(i)], "score": float(outputs[i])}
        for i in top_indices
    ]
    return JSONResponse({"predictions": results})

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8080)
EOF

python3 /workspace/onnx_api.py &

# API का परीक्षण करें
curl -X POST "http://localhost:8080/predict" \\
    -H "accept: application/json" \\
    -F "file=@test_image.jpg"
```

***

## चरण 9 — GPU उपयोग की निगरानी करें

```bash
# इन्फ़रेंस के दौरान रियल-टाइम GPU निगरानी
watch -n 0.5 nvidia-smi

# या बेहतर UI के लिए nvitop का उपयोग करें
pip install nvitop
nvitop
```

***

## प्रदर्शन बेंचमार्क

| मॉडल      | GPU      | प्रदाता       | थ्रूपुट (inf/sec) |
| --------- | -------- | ------------- | ----------------- |
| ResNet50  | RTX 4090 | CUDA          | \~4,200           |
| ResNet50  | RTX 4090 | TensorRT FP16 | \~8,500           |
| BERT Base | RTX 4090 | CUDA          | \~380             |
| BERT Base | RTX 4090 | TensorRT FP16 | \~720             |
| YOLOv8n   | RTX 3090 | CUDA          | \~1,800           |
| YOLOv8x   | A100     | TensorRT FP16 | \~920             |

***

## समस्या निवारण

### CUDA प्रदाता उपलब्ध नहीं है

```bash
# जाँचें कि CUDA ORT इंस्टॉल है (CPU-only संस्करण नहीं)
pip uninstall onnxruntime
pip install onnxruntime-gpu

python3 -c "import onnxruntime as ort; print(ort.get_available_providers())"
```

### TensorRT संकलन त्रुटियाँ

```bash
# TensorRT संस्करण संगतता जाँचें
python3 -c "import tensorrt; print(tensorrt.__version__)"

# इसके बजाय CUDA EP का उपयोग करें
providers = ["CUDAExecutionProvider"]  # TensorRT EP छोड़ें
```

### आकार असंगति त्रुटियाँ

```python
# मॉडल इनपुट/आउटपुट आकार जाँचें
for input in session.get_inputs():
    print(f"Input: {input.name}, shape: {input.shape}, type: {input.type}")

for output in session.get_outputs():
    print(f"Output: {output.name}, shape: {output.shape}, type: {output.type}")
```

***

## उन्नत: मल्टी-मॉडल पाइपलाइन

```python
import onnxruntime as ort
import numpy as np

class MultiModelPipeline:
    def __init__(self):
        providers = ["CUDAExecutionProvider"]
        self.detector = ort.InferenceSession("detector.onnx", providers=providers)
        self.classifier = ort.InferenceSession("classifier.onnx", providers=providers)
    
    def run(self, image: np.ndarray) -> list:
        # चरण 1: ऑब्जेक्ट डिटेक्शन
        boxes = self.detector.run(None, {"image": image})[0]
        
        results = []
        for box in boxes:
            # पता लगाए गए क्षेत्र को काटें
            crop = self._crop(image, box)
            
            # चरण 2: प्रत्येक क्षेत्र को वर्गीकृत करें
            label = self.classifier.run(None, {"input": crop})[0]
            results.append({"box": box.tolist(), "label": int(label.argmax())})
        
        return results
    
    def _crop(self, image, box):
        x1, y1, x2, y2 = box.astype(int)
        return image[:, :, y1:y2, x1:x2]

pipeline = MultiModelPipeline()
```

***

## अतिरिक्त संसाधन

* [ONNX Runtime GitHub](https://github.com/microsoft/onnxruntime)
* [ONNX Runtime दस्तावेज़ीकरण](https://onnxruntime.ai/docs/)
* [Hugging Face Optimum](https://huggingface.co/docs/optimum/)
* [ONNX Model Zoo](https://github.com/onnx/models) — पहले से निर्यातित मॉडल
* [Netron](https://netron.app/) — ONNX मॉडल विज़ुअलाइज़र
* [ONNX Runtime Python API](https://onnxruntime.ai/docs/api/python/)

***

*Clore.ai पर ONNX Runtime उन उत्पादन इन्फ़रेंस सेवाओं के लिए आदर्श विकल्प है जिन्हें अधिकतम GPU दक्षता के साथ विभिन्न फ्रेमवर्क से मॉडल सर्व करने की आवश्यकता होती है।*

***

## Clore.ai GPU अनुशंसाएँ

| उपयोग-प्रकरण             | अनुशंसित GPU    | Clore.ai पर अनुमानित लागत                 |
| ------------------------ | --------------- | ----------------------------------------- |
| विकास/परीक्षण            | RTX 3090 (24GB) | $0.07–0.21/gpu/hr                         |
| प्रोडक्शन इन्फरेंस       | RTX 4090 (24GB) | $0.14–0.42/gpu/hr                         |
| बड़े पैमाने पर परिनियोजन | A100 80GB       | [bare metal](https://clore.ai/bare-metal) |

> 💡 इस गाइड के सभी उदाहरण [Clore.ai](https://clore.ai/marketplace) GPU servers पर तैनात किए जा सकते हैं। उपलब्ध GPUs ब्राउज़ करें और घंटे के हिसाब से किराए पर लें — कोई प्रतिबद्धता नहीं, पूर्ण root access.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-hi/gpu-devops/onnx-runtime.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
