تاريخ النشر
نشر نماذج الذكاء الاصطناعي: Docker وKubernetes وMLOps في الإنتاج
انقل نماذج الذكاء الاصطناعي من الدفتر إلى الإنتاج: صور Docker وخدمة LLM وKubernetes مع جدولة GPU والتوسع التلقائي وCI/CD والإصدارات التجريبية والمراقبة.
- بقلم
- Ali Özdurmuşالمؤسس، Veni AI
- تاريخ التحديث
- مدة القراءة
- قراءة في 6 دقيقة

نشر نموذج الذكاء الاصطناعي يعني نقله من الدفتر (notebook) إلى بيئة إنتاج يكون فيها موثوقًا وقابلًا للتوسع والصيانة. وسواء كنت تقدّم نموذجك المضبوط بدقة، أو تشغّل LLM مفتوح الأوزان على وحدات GPU الخاصة بشركتك، أو تغلّف واجهة API مستضافة في خدمة خاصة بك، فإن الأساسيات الهندسية نفسها تنطبق.
أنماط النشر
1. الاستدلال الدفعي
معالجة البيانات على دفعات ومهام مجدولة:
Data Lake → Batch Job → Model Inference → Results Storage2. الاستدلال في الزمن الحقيقي
تنبؤات فورية عبر API:
Request → API Gateway → Model Server → Response3. الاستدلال المتدفق
معالجة تدفق مستمر من البيانات:
Kafka Stream → Stream Processor → Model → Output Stream4. النشر على الحافة (Edge)
الاستدلال على الجهاز نفسه:
Mobile/IoT Device → Optimized Model → Local Inferenceتحويل النموذج إلى حاويات باستخدام Docker
ملف Dockerfile الأساسي
FROM python:3.11-slim
WORKDIR /app
# System dependencies
RUN apt-get update && apt-get install -y \
libgomp1 \
&& rm -rf /var/lib/apt/lists/*
# Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Model and code
COPY model/ ./model/
COPY src/ ./src/
# Port
EXPOSE 8000
# Healthcheck
HEALTHCHECK \
CMD curl -f http://localhost:8000/health || exit 1
# Start command
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"]البناء متعدد المراحل
# Build stage
FROM python:3.11 AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip wheel --no-cache-dir --wheel-dir /wheels -r requirements.txt
# Production stage
FROM python:3.11-slim
WORKDIR /app
COPY /wheels /wheels
RUN pip install --no-cache-dir /wheels/*
COPY . .
CMD ["python", "main.py"]دعم GPU
FROM nvidia/cuda:12.1.1-runtime-ubuntu22.04
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
# Python installation
RUN apt-get update && apt-get install -y python3 python3-pip
# PyTorch GPU
RUN pip3 install torch --index-url https://download.pytorch.org/whl/cu121
COPY . /app
WORKDIR /app
CMD ["python3", "inference.py"]أطر خدمة النماذج
خادم FastAPI
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import torch
model = None
@asynccontextmanager
async def lifespan(app: FastAPI):
global model
model = torch.load("model.pt") # load once at startup
model.eval()
yield
app = FastAPI(lifespan=lifespan)
class PredictionRequest(BaseModel):
text: str
class PredictionResponse(BaseModel):
prediction: str
confidence: float
@app.post("/predict", response_model=PredictionResponse)
async def predict(request: PredictionRequest):
if model is None:
raise HTTPException(500, "Model not loaded")
with torch.no_grad():
output = model(request.text)
return PredictionResponse(
prediction=output["label"],
confidence=output["score"]
)
@app.get("/health")
async def health():
return {"status": "healthy", "model_loaded": model is not None}TorchServe
# Create model archive
torch-model-archiver \
--model-name mymodel \
--version 1.0 \
--model-file model.py \
--serialized-file model.pt \
--handler handler.py
# Start serving
torchserve --start \
--model-store model_store \
--models mymodel=mymodel.marTriton Inference Server
# config.pbtxt
name: "text_classifier"
platform: "pytorch_libtorch"
max_batch_size: 32
input [
{
name: "INPUT__0"
data_type: TYPE_INT64
dims: [ -1 ]
}
]
output [
{
name: "OUTPUT__0"
data_type: TYPE_FP32
dims: [ -1, 2 ]
}
]
instance_group [
{ count: 2, kind: KIND_GPU }
]خدمة نماذج LLM
بالنسبة إلى نماذج اللغة مفتوحة الأوزان، استخدم محرك استدلال مخصصًا مثل vLLM أو SGLang بدلًا من خادم تكتبه يدويًا. فهذه المحركات تتولى تجميع الطلبات في دفعات وإدارة ذاكرة KV-cache، وتدعم النماذج المكمَّمة، وتوفّر نقاط وصول متوافقة مع OpenAI، فيستطيع التطبيق التبديل بين نموذج مستضاف ذاتيًا ونموذج مستضاف لدى مزوّد بمجرد تغيير عنوان base URL.
النشر على Kubernetes
النشر الأساسي
apiVersion: apps/v1
kind: Deployment
metadata:
name: model-server
spec:
replicas: 3
selector:
matchLabels:
app: model-server
template:
metadata:
labels:
app: model-server
spec:
containers:
- name: model-server
image: myregistry/model-server:v1.0
ports:
- containerPort: 8000
resources:
requests:
memory: "2Gi"
cpu: "1"
limits:
memory: "4Gi"
cpu: "2"
livenessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 8000
initialDelaySeconds: 5
periodSeconds: 5النشر مع GPU
apiVersion: apps/v1
kind: Deployment
metadata:
name: gpu-model-server
spec:
replicas: 2
template:
spec:
containers:
- name: model
image: myregistry/gpu-model:v1.0
resources:
limits:
nvidia.com/gpu: 1
nodeSelector:
accelerator: nvidia-tesla-t4
tolerations:
- key: "nvidia.com/gpu"
operator: "Exists"
effect: "NoSchedule"Horizontal Pod Autoscaler
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: model-server-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: model-server
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Pods
pods:
metric:
name: requests_per_second
target:
type: AverageValue
averageValue: 100Service وIngress
apiVersion: v1
kind: Service
metadata:
name: model-service
spec:
selector:
app: model-server
ports:
- port: 80
targetPort: 8000
type: ClusterIP
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: model-ingress
annotations:
nginx.ingress.kubernetes.io/rate-limit: "100"
spec:
rules:
- host: model.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: model-service
port:
number: 80مسار MLOps
مسار CI/CD
# .github/workflows/mlops.yml
name: MLOps Pipeline
on:
push:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run tests
run: pytest tests/
train:
needs: test
runs-on: ubuntu-latest
steps:
- name: Train model
run: python train.py
- name: Evaluate model
run: python evaluate.py
- name: Register model
if: success()
run: python register_model.py
deploy:
needs: train
runs-on: ubuntu-latest
steps:
- name: Build image
run: docker build -t model:${{ github.sha }} .
- name: Push to registry
run: docker push myregistry/model:${{ github.sha }}
- name: Deploy to K8s
run: kubectl set image deployment/model model=myregistry/model:${{ github.sha }}سجل النماذج
import mlflow
# Registering model
with mlflow.start_run():
mlflow.log_params({"learning_rate": 0.001, "epochs": 10})
mlflow.log_metrics({"accuracy": 0.95, "f1": 0.93})
mlflow.pytorch.log_model(model, "model")
# Loading model
model_uri = "models:/text-classifier/production"
model = mlflow.pytorch.load_model(model_uri)النشر التجريبي (Canary)
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: model-service
spec:
hosts:
- model-service
http:
- route:
- destination:
host: model-service-v1
weight: 90
- destination:
host: model-service-v2
weight: 10المراقبة
مقاييس Prometheus
from prometheus_client import Counter, Histogram, start_http_server
PREDICTIONS = Counter('predictions_total', 'Total predictions', ['model', 'status'])
LATENCY = Histogram('prediction_latency_seconds', 'Prediction latency')
@LATENCY.time()
def predict(input_data):
result = model(input_data)
PREDICTIONS.labels(model='v1', status='success').inc()
return resultلوحة Grafana
أهم المقاييس التي ينبغي مراقبتها:
- معدل الطلبات (RPS)
- زمن الاستجابة (p50 وp95 وp99)
- معدل الأخطاء
- استخدام GPU
- استهلاك الذاكرة
- مؤشرات انجراف النموذج (drift)
الخلاصة
يقوم الذكاء الاصطناعي الموثوق في الإنتاج على أسس مألوفة: حاويات قابلة لإعادة الإنتاج، وطبقة خدمة تناسب النموذج، وKubernetes للتوسع وجدولة GPU، وCI/CD مع بوابات تقييم، وإصدارات تدريجية، ومراقبة تشمل إشارات خاصة بالنماذج مثل الانجراف.
تنشر Veni AI تطبيقات الذكاء الاصطناعي على السحابة وفي البنية المحلية (on-premise) وعلى بنية مستضافة داخل تركيا، وتسلّم مسارات يستطيع فريقك تشغيلها. اطّلع على خدماتنا أو تحدّث إلى مهندسينا.


