Unsloth を用いた Amazon SageMaker AI 上の量子化モデルのデプロイ
AWS は Unsloth とのコラボ記事で、大規模言語モデルのメモリ効率を劇的に向上させる動的量子化技術の実装パターンと運用プラクティスを解説し、コスト削減と推論速度の向上を実現する方法を示している。
キーポイント
Unsloth の動的量子化技術の概要
16 ビットモデルを 4 ビットに量子化する際、精度低下を防ぐために一部の層を高ビットのまま維持する「動的量子化」により、メモリ使用量を大幅に削減しつつ精度を維持できる。
AWS 上での 4 つの展開パターン
EC2 による直接アクセス、SageMaker AI 推論エンドポイント、EKS/ECS によるコンテナ基盤への統合など、ユースケースに応じた 4 つの主要なデプロイ戦略を提示している。
コストとパフォーマンスの実践的メリット
量子化によりメモリ使用量が約 75% 削減され、マルチ GPU インスタンスからシングル GPU への移行が可能となり、推論コストや起動時間の短縮が期待できる。
本番環境向けの運用プラクティス
単なる技術解説に加え、安定したサービス提供のための運用上のベストプラクティスについても言及しており、実装から生産環境への移行を支援する内容となっている。
SageMaker での GGUF デプロイ構成
GGUF モデルを SageMaker エンドポイントとして運用するには、llama.cpp を含むカスタムコンテナを作成し、ポート 8080 で /ping および /invocations エンドポイントを実装する必要があります。
コストと性能の比較検証
Unsloth の動的量子化モデル(Q4_K_XL)を llama.cpp で実行する構成は、フル精度の BF16 変種と比較して大幅なコスト削減(約 $1.41/時間対 $7.09/時間)を実現します。
Nginx を用いたプロキシ設定
SageMaker の標準インターフェースを満たすために、nginx リバースプロキシを使用して /ping と /invocations を内部の llama-server エンドポイントにマッピングします。
影響分析・編集コメントを表示
影響分析
この記事は、大規模言語モデルの推論コストを劇的に削減できる技術的解決策(Unsloth の動的量子化)と、それを AWS エコシステム上で実装するための具体的なロードマップを提供しています。企業にとって、AI モデルのスケーラビリティを維持しつつインフラコストを最適化する重要な指針となり、特にリソース制約のある環境での LLM 導入を加速させる効果が期待されます。
編集コメント
AWS と Unsloth の連携により、高価な GPU インフラへの依存を減らしつつ高精度な推論を実現する現実的な道筋が示されています。特にコスト最適化が急務の企業にとって、即座に検討すべき技術的アプローチと言えます。
*この投稿は、Unsloth の Daniel Han 氏と Michael Han 氏との共著です。*
16 ビット浮動小数点精度(BF16 または FP16)で保存された大規模基盤モデル(FMs: Foundation Models)のデプロイは高価になります。これには大規模な GPU インスタンスが必要となり、サービングコストが上昇し、反復サイクルが遅くなります。量子化(Quantization)は、モデルの重みの数値精度を低下させることでこの課題に対処します(例えば 16 ビットから 4 ビットへ)。これによりメモリ使用量が大幅に削減されます。量子化の欠点は、モデルの精度が低下する可能性があることです。ここで注目されるのが動的量子化(Dynamic Quantization)です。適切に行えば、動的量子化はメモリ使用量を削減しつつ精度を維持することができます。インスタンスコスト、ストレージ、起動時間の節約は、スケールが大きくなるにつれて複利のように蓄積していきます。
本稿では、Unsloth で既に量子化されたモデルを AWS インフラストラクチャ上でデプロイするための 4 つのデプロイパターンについて学びます。これらのパターンには、直接インスタンスアクセスのために Amazon Elastic Compute Cloud(Amazon EC2)を使用する方法、管理型サービングのための Amazon SageMaker AI 推論エンドポイントを使用する方法、そして推論が既存のコンテナフレームワークに収まる必要がある場合に Amazon Elastic Kubernetes Service(Amazon EKS)または Amazon Elastic Container Service(Amazon ECS)を使用する方法が含まれます。また、本稿では本番環境向けの運用プラクティスについても学びます。
Unsloth ダイナミック量子化とは何ですか?
Unsloth の共同創設者である Daniel Han は 以下のように説明しています:
**
*「強力なモデルの最大の課題は、そのサイズが非常に大きく、このモデルを実行するには 1.5TB のストレージが必要になることです。いくつかの工夫を施すことで、モデルのサイズを 217GB に縮小できます。86% 小さくなったので精度も 86% 低下するだろうと思うかもしれませんが、実際にはそうではなく、精度はわずか 14% しか低下しません。この手法を私たちは『ダイナミック量子化』と呼びます。すべての重みを 4 ビットまで量子化するのではなく、一部の層はより高い 8 ビットのまま維持することで、モデルのディスク容量を削減できることを多くのベンチマークで示しています。」*
**
実用的な観点から、量子化とは各重みを格納するために使用されるビット数を減らすことです。標準的な BF16 モデルではパラメータあたり 16 ビットを使用します。4 ビットへの量子化によりサイズは 75% 削減されますが、実際のファイルサイズは量子化のメタデータのためわずかに大きくなります。80 億パラメータを持つモデルの場合、メモリ使用量は約 16GB から約 5GB に減少します。これは、マルチ GPU インスタンスが必要になるか、単一の GPU で快適に動作するかを分ける決定的な違いとなることがよくあります。
Unsloth は、ファウンデーションモデルの微調整(fine-tuning)と量子化のためのツールです。Unsloth Dynamic は、均一な圧縮を超えた量子化手法です。すべての層に同じビット削減を適用するのではなく、以下の 3 つのステップで動作します:
- レイヤーごとの分析 – Unsloth は、各レイヤーが精度低下に対してどの程度敏感かを測定します。
- 動的ビット割り当て – 重要なレイヤー(精度の低下が出力の有意な劣化を引き起こすもの)は高い精度(例えば 16 ビット)で維持され、感度の低いレイヤーは積極的に量子化(4 ビット以下)されます。
- 精度調整 – 量子化は、ディスク使用量を可能な限り小さく保ちつつ、結合された出力品質が元のモデルにできるだけ近くなるように調整されます。
このプロセスの最終目標は、モデルサイズを有意な程度圧縮しながらも、量子化済みモデルと標準モデルとの間の精度差を可能な限り小さくすることです。オープンソースの Unsloth パッケージを使用すれば、ファインチューニング、実行、エクスポート、デプロイまでを一元的なワークフローで実現できます。
AWS でデプロイする際、量子化は重要な意味を持ちます。なぜなら、それは同時に 3 つの要素を変化させるからです。第一に、インスタンスタイプの決定です。本来であれば大規模な GPU を必要とするような大型モデルでも、量子化によってより小規模なインスタンス、あるいは CPU 上でも実用的になる可能性があります。第二に、起動時およびストレージのプロファイルです。モデルファイルが小さくなることで、環境間での移動、保存、プロモーションが高速化されます。第三に、デプロイの柔軟性です。コスト重視の推論には小規模なモデルファイルを選択したり、品質重視の推論には高忠実度のエクスポートを使用したり、スループットの高い GPU サービングには統合された表現を選んだりできます。この柔軟性が、AWS 環境において Unsloth を有用にする理由です。Unsloth を用いることで、すべてのデプロイを同じランタイムやハードウェアの前提条件に強制するのではなく、モデルをサービングパスに合わせて適応させることが可能になります。
どのモデル形式を使用するか
Unsloth のデプロイワークフローにおける重要な原則は、出力アーティファクトがサービング設計を主導すべきであるという点です。インフラストラクチャの選定はその後です。まずアーティファクトとランタイムを選択し、そのランタイムを運用モデルに合致する AWS サービス上に配置します。
Unsloth は、デプロイ指向の出力タイプを複数サポートしています:
- GGUF ファイル – GGUF は、モデルの重み、トークナイザー、メタデータを単一ファイルにパッケージ化する形式であり、自己完結型で追加ファイルなしでロード可能です。llama.cpp、Ollama、Unsloth といった軽量ランタイム向けにご利用ください。AWS では、これは Amazon EC2 または Amazon SageMaker AI カスタムコンテナに対応します。
- マージされた safetensors 重み – (16 ビット、8 ビット、FP8 4-bit、NVFP4) は、Unsloth を通じて vLLM や SGLang といった高スループットエンジン向けに作成可能です。AWS では、これは Amazon SageMaker AI Large Model Inference (LMI) コンテナ、Amazon EKS、または Amazon ECS に対応します。
実践的なデプロイメントマップ
以下の表は、各アーティファクトタイプを最適なランタイムと AWS ターゲットにマッピングしたもので、要件に合致するデプロイパターンをすばやく特定できるようになっています。
| Artifact** | Best-fit runtime | Best-fit AWS target | Use when |
|---|---|---|---|
| GGUF | llama.cpp / llama-server または Unsloth | Amazon EC2 | インスタンスへの直接アクセスを伴う、手元のテストへの最速パス |
| GGUF | カスタムコンテナ内の llama.cpp または Unsloth | Amazon SageMaker AI | オートスケーリング機能を備えた管理されたエンドポイントと軽量ランタイム |
| マージされた 16 ビットまたは 4-bit 重み | vLLM / SGLang / LMI バックエンド | Amazon SageMaker AI | 高スループット、バッチ処理、オートスケーリング、本番環境での GPU サービング
コンテナ化されたスタック
ご自身の好みのランタイム
Amazon EKS または Amazon ECS
推論は既存のコンテナフレームワークに統合される必要があります
本記事の各デプロイパターンは、以下の一般的なワークフローに従います:
- Unsloth でモデルをファインチューニングするか、ダウンロードする。
- 目的のランタイムに適合したモデルファイルをエクスポートする。
- ローカル環境または Amazon EC2 上でランタイムを検証する。
- 同じモデルファイルとランタイムの組み合わせを、マネージド型または環境ネイティブなデプロイ先に昇格させる。
この順序は、後々の予期せぬ動作(特にメモリ使用量、プロンプトフォーマット、レイテンシ挙動に関するもの)を防ぐために役立ちます。
パターン 1: llama.cpp と Unsloth を用いた Amazon EC2 上の GGUF
このパターンは、インスタンスへの直接アクセスを通じて量子化レベルを迅速に検証するために使用します。多くのユースケースにおいて、Amazon EC2 は最小限の抽象化で最大限の制御を得られるため、強力な出発点となります。管理エンドポイント設計へ着手する前に、複数の量子化レベルでのベンチマーク実行、プロンプトフォーマットのテスト、CPU と GPU の挙動比較、実際のメモリフットプリントの把握を行います。
典型的な Unsloth エクスポートは以下のようになります:
model.save_pretrained_gguf("gguf_model", tokenizer, quantization_method="q4_k_xl")必ず JSON 形式で返してください。translation フィールドのみ。他のフィールド (technical_terms 等) は一切追加しないこと — 余計なフィールドを書こうとして本文翻訳がトークン上限で打ち切られる事故を防ぐため:
{"translation": "翻訳全文"}
これにより、ローカルの llama.cpp ベースの推論に使用できる GGUF ファイルが生成されます。コンパニオンリポジトリでは、量子化されたエンドポイントに q4_k_xl を使用しています。異なる量子化手法は、ファイルサイズと出力忠実度の間のトレードオフを制御します:より高い出力忠実度を得るには q8_0 を使用し(ファイルサイズは約 2 倍)、量子化による損失のない完全精度の GGUF を得るには f16 を使用してください。量子化手法の一覧とその特性については、Unsloth GGUF ドキュメント を参照してください。
GGUF が完成したら、最小限の llama-server 起動には以下の設定が必要です:
llama-server \
--model /models/my-model.gguf \
--alias my-model \
--ctx-size 8192 \
--host 0.0.0.0 \
--port 8080
unsloth run \
--model /models/my-model.gguf \
--alias my-model \
--ctx-size 8192 \
--host 0.0.0.0 \
--port 8080
この時点で、アプリケーションは OpenAI 互換インターフェースを介してモデルと通信できるようになります:
from openai import OpenAI
client = OpenAI(
base_url="http://:8080/v1",
api_key="not-required",
)
response = client.chat.completions.create(
model="my-model",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain AWS Graviton in two sentences."},
],
max_tokens=128,
)
print(response.choices[0].message.content)
**
image 重要:** この設定は隔離されたテスト環境に適しています。本番環境では、セキュリティグループを既知のクラスレス・ドメイン間ルーティング (CIDR: Classless Inter-Domain Routing) ブロックに制限し、プライベートインターフェース(例:127.0.0.1)にバインドし、エンドポイントを認証済み API ゲートウェイまたはロードバランサーの背後に配置してください。
このパスが魅力的である理由は 3 つあります。デバッグ時に透明性が高く、アップストリームのランタイム動作に近い挙動を示すためです。また、コンテナ契約、自動スケーリングポリシー、エンドポイントガバナンスを追加する前に、量子化の選択肢をテストするためのクリーンな場所を提供します。
Amazon EC2 は、実用的なデプロイメントに関する課題を評価するための最も直接的な場所でもあります。
- 量子化の品質 – q4_k_m と q8_0 のように、異なる量子化レベル間の出力を、特定の評価基準に対して比較してください。品質への影響はモデルアーキテクチャやタスクによって異なります。
- ハードウェア要件 – モデルのメモリフットプリントが利用可能な CPU RAM を超える場合、GPU ベースのインスタンスが必要です。推論時のピークメモリ使用量を確認し、単にモデルの読み込み時だけでなく注意してください。最良のパフォーマンスを得るためには、モデル全体をメモリにロードできる十分な RAM または VRAM を確保してください。例えば、モデルが 128 GB のディスク容量を持つ場合、利用可能な RAM または VRAM は 128 GB よりも大きくする必要があります。
- コンテキスト長のトレードオフ – より長いコンテキストウィンドウは、レイテンシとメモリ消費量の両方を増加させます。ワークロードに最適なバランスを見つけるために、代表的なプロンプト長でテストを行ってください。
- チャットテンプレートの検証 – 「system」や「user」といった役割をモデルが期待するトークンシーケンスにマッピングする構造化されたプロンプト形式が、トレーニング環境外でも一貫した動作を生み出すことを確認してください。
評価、内部ツール、概念実証(PoC)、および初期の生産パイロットにおいては、Amazon EC2 が多くの場合適切な出発点となります。
パターン 2:カスタムコンテナを使用した Amazon SageMaker AI 上の GGUF
高速な反復開発には Amazon EC2 が推奨されますが、これは管理された推論サービスをそのまま提供してくれるものではありません。オートスケーリング、モニタリング、AWS Identity and Access Management (IAM) の統合、そして安定した API サフェースを備えた本番環境用のエンドポイントが必要な場合、Amazon SageMaker AI 推論エンドポイントの方がより適しています。
GGUF デプロイメントにおいて、最も実用的な設計は通常、GGUF モデルファイルを llama.cpp やその他の軽量ランタイムと共にパッケージ化したカスタム推論コンテナです。このコンテナは Amazon SageMaker AI ホーシングインターフェースを公開する必要があり、具体的にはポート 8080 でリッスンし、ヘルスチェック用に /ping を実装し、推論リクエスト用に /invocations を実装する必要があります。
コマンニオン GitHub リポジトリ には、このパターンの完全な動作例が含まれています。ここでは、Unsloth の動的量子化 Qwen3-VL-8B-Instruct (Q4_K_XL GGUF を llama.cpp でサービスし、ml.g5.xlarge 上で約 $1.41/時間) と、フル精度の BF16 バリアント (vLLM でサービスし、ml.g5.12xlarge 上で約 $7.09/時間) の並列比較デプロイが行われます。料金は 2026 年 6 月時点のものですが、現在のレートについては Amazon SageMaker AI プライシングページ をご参照ください。エントリーポイントスクリプトは内部ポートで llama-server を起動し、nginx をリバースプロキシとして使用して Amazon SageMaker AI のインターフェース要件を満たします:
GGUF モデルとビジョン投影器を使用して llama-server を起動
/app/llama-server \
--model /models/Qwen3-VL-8B-Instruct-UD-Q4_K_XL.gguf \
--mmproj /models/mmproj-F16.gguf \
--host 0.0.0.0 \
--port 8081 \
--ctx-size 4096
Nginx はその後、/ping を llama-server のヘルスチェックに、/invocations をチャット完了エンドポイントにマッピングします。これにより、Amazon SageMaker AI に標準的なインターフェースを提供しつつ、ランタイムを軽量に保つことができます:
SageMaker のヘルスチェックエンドポイント
location /ping {
proxy_pass http://llama_backend/health;
}
SageMaker 推論エンドポイント -> llama.cpp チャット完了
location /invocations {
proxy_pass http://llama_backend/v1/chat/completions;
proxy_read_timeout 120s;
}
一般的なアーキテクチャは以下のようになります:
- 完成した GGUF モデルファイルを Amazon Simple Storage Service (Amazon S3) に保存します。
- Amazon SageMaker AI コンテナを起動し、モデルを /opt/ml/model 下に配置します。
- ローカルのモデルファイルに対して llama.cpp または Unsloth を起動します。
- Amazon SageMaker AI のリクエストをローカル推論呼び出しに変換する薄い API レイヤーを公開します。
コンパニオン GitHub リポジトリにある以下のアーキテクチャ図では、サンプルが量子化された GGUF エンドポイント(このパターン)とフル精度の vLLM エンドポイント(パターン 3)の両方をどのようにデプロイするかを示しています。フローは次の通りです:

*図:コンパニオンサンプルデプロイメントのアーキテクチャ図。*
- Terraform は、Amazon Elastic Container Registry (Amazon ECR)、AWS CodeBuild、および Amazon S3 リソースを含むすべてのインフラストラクチャをプロビジョニングします。
- AWS CodeBuild がカスタムコンテナイメージをビルドし、それを Amazon ECR にプッシュします。
- Amazon SageMaker AI は、仮想プライベートクラウド (VPC) 内に 2 つのリアルタイムエンドポイントを作成します。1 つは量子化された GGUF モデル用(パターン 2)、もう 1 つはフル精度モデル用(パターン 3)です。
- 両方のエンドポイントは、起動時にそれぞれのモデルファイルを Amazon S3 からプルします。
- Amazon SageMaker Notebook Instance は、両方のエンドポイントに対する評価を実行するための比較用ノートブックへのアクセスを提供します。
このパターンは、ランタイムを軽量に保ちつつ、Amazon SageMaker AI がプロダクションで重要な運用上の懸念(エンドポイントのライフサイクルや自動スケーリングなど)を処理するためによく機能します。小規模なモデルの場合、CPU ベースのエンドポイント上では特に魅力的です。より大規模な量子化モデルや低遅延要件がある場合は、同じ設計を GPU ベースのエンドポイントに移動できます。
トレードオフとして、llama.cpp は推論/デプロイメントエンジンですが、完全なサービングシステムではありません。Amazon SageMaker AI においては、Amazon SageMaker AI エンドポイントのように動作するコンテナが依然として必要です。このラッパー層には大きな実装努力は不要ですが、それはプロダクション設計において重要な部分です。
パターン 3:GPU 最適化サービングエンジンを用いた Amazon SageMaker AI 上の統合重み
GGUF は、モデルファイルサイズと軽量なサービングが最優先事項である場合に優れています。しかし、スループットや GPU の効率性を最優先する場合には、必ずしも最適な選択肢とは限りません。そのようなシナリオでは、統合された重みがより魅力的になります。
統合された重みとは、単一の統一された safetensors 形式の重みセットとして保存されたモデルを指します。これは通常、微調整アダプター(Low-Rank Adaptation (LoRA) など)とベースモデルを組み合わせた結果ですが、デプロイ準備が整った形式で直接保存されたベースモデルにも適用されます。Unsloth は、統合 16 ビットおよび統合 4 ビットの出力、ならびに LoRA のみのエクスポートに対応する保存パスをサポートしています。これらは、バッチ処理、高いトークンスループット、マルチ GPU スケーリングといった本番環境向けの GPU サービングパターンを中心に構築された vLLM や SGLang などのランタイムとより親和性が高いものです。
代表的なエクスポートは以下のようになります:
model.save_pretrained_merged(
"finetuned_model",
tokenizer,
save_method="merged_16bit",
)
サービングパスは以下の通りです:
vllm serve finetuned_model
AWS では、Amazon SageMaker AI で利用可能な LMI コンテナが特に重要です。コンパニオンサンプル のフル精度エンドポイントにおいて、Amazon SageMaker AI 用の LMI コンテナは、Terraform モデルリソース上の環境変数を通じて完全に構成されます:
HF_MODEL_ID = "Qwen/Qwen3-VL-8B-Instruct"
OPTION_DTYPE = "bf16"
OPTION_ROLLING_BATCH = "vllm"
OPTION_TENSOR_PARALLEL_DEGREE = "4"
OPTION_MAX_MODEL_LEN = "4096"
カスタムコンテナは不要です。LMI コンテナは、<a href="https://huggingface.co/Qwen/Qwen3-VL-8B-Instruct" target="_blank
原文を表示
*This post was co-written with Daniel Han and Michael Han from Unsloth.*
Deploying large foundation models (FMs) stored at their original 16-bit floating-point precision (BF16 or FP16) is expensive. They need large GPU instances, driving up serving costs, and slowing down iteration cycles. Quantization addresses this by reducing the numerical precision of a model’s weights (for example from 16-bit to 4-bit), which shrinks the memory usage significantly. The drawback of quantization is that it can reduce the accuracy of a model, which is where dynamic quantization becomes compelling. When done correctly, dynamic quantization can reduce memory usage while maintaining accuracy. The savings in instance cost, storage, and startup time can compound quickly at scale.
In this post, you will learn four deployment patterns for taking models that have already been quantized with Unsloth and deploying them on AWS infrastructure. The patterns use Amazon Elastic Compute Cloud (Amazon EC2) for direct instance access, Amazon SageMaker AI inference endpoints for managed serving, and Amazon Elastic Kubernetes Service (Amazon EKS) or Amazon Elastic Container Service (Amazon ECS) when inference needs to fit into an existing container framework. You also learn operational practices for production deployments.
What is Unsloth Dynamic quantization?
As Daniel Han, co-founder of Unsloth, explains:
“The biggest problem of a powerful model is it’s very big and you need 1.5TB to run this model. By using some tricks you can make the model 217GB in size. You might think because it’s 86% smaller, accuracy will degrade by 86%, but that’s not the case, it only degrades by 14% accuracy. This methodology we call it dynamic quantization and we show many benchmarks where you can reduce the disk space of the model, by not quantizing all weights down to 4-bit etc. but some layers remain in higher 8-bits.”
In practical terms, quantization reduces the number of bits used to store each weight. A standard BF16 model uses 16 bits per parameter. Quantizing to 4-bit shrinks the size by 75 percent, though real-world file sizes are slightly larger because of quantization metadata. For an 8-billion parameter model, that takes the memory footprint from approximately 16 GB down to approximately 5 GB. That’s often the difference between needing a multi-GPU instance and fitting comfortably on a single GPU.
Unsloth is a tool for fine-tuning and quantizing foundation models. Unsloth Dynamic is a quantization methodology that goes beyond uniform compression. Rather than applying the same bit reduction to every layer, it works in three steps:
- Layer-by-layer analysis – Unsloth measures how sensitive each layer is to precision loss.
- Dynamic bit allocation – Important layers (those where precision loss causes meaningful output degradation) are kept at higher precision (for example, 16-bit), while less sensitive layers are quantized aggressively (4-bit or lower).
- Precision tuning – The quantization is tuned so that the combined output quality remains as close as possible to the original, while keeping disk space usage as small as possible.
The end goal of this process is to make the accuracy differences between the quantized model and the standard model as small as possible, while also compressing the model size by a meaningful amount. With the open source Unsloth package, you can fine-tune, run, export, and deploy models in one unified workflow.
When you deploy on AWS, quantization matters because it changes three things simultaneously. First, the instance decision: a large model that would otherwise require larger GPUs might become practical on a smaller one, or even on CPU. Second, the startup and storage profile: smaller model files move, store, and promote across environments faster. Third, the deployment flexibility: you can choose a smaller model file for cost-sensitive inference, a higher-fidelity export for quality-sensitive inference, or a merged representation for higher-throughput GPU serving. That flexibility is what makes Unsloth useful in an AWS environment. With it, you can adapt the model to the serving path instead of forcing every deployment into the same runtime and hardware assumptions.
Which model format to use
A key principle in the Unsloth deployment workflow is that the output artifact should drive the serving design. Infrastructure selection comes second. First, choose the artifact and runtime, then place that runtime on the AWS service that matches your operating model.
Unsloth supports multiple deployment-oriented output types:
- GGUF files – GGUF is a single-file format that packages model weights, tokenizer, and metadata together, making it self-contained and ready to load without additional files. Use these for lightweight runtimes such as llama.cpp, Ollama, and Unsloth. On AWS, this maps to Amazon EC2 or an Amazon SageMaker AI custom container.
- Merged safetensors weights – (16-bit, 8-bit, FP8 4-bit, NVFP4) can be created through Unsloth for higher-throughput engines such as vLLM and SGLang. On AWS, this maps to Amazon SageMaker AI Large Model Inference (LMI) containers, Amazon EKS, or Amazon ECS.
A practical deployment map
The following table maps each artifact type to its best-fit runtime and AWS target, so you can quickly identify which deployment pattern matches your requirements.
Artifact
Best-fit runtime
Best-fit AWS target
Use when
GGUF
llama.cpp / llama-server or Unsloth
Amazon EC2
Fastest path to hands-on testing with direct instance access
GGUF
llama.cpp in a custom container or Unsloth
Amazon SageMaker AI
Managed endpoints with autoscaling, lightweight runtime
Merged 16-bit or 4-bit weights
vLLM / SGLang / LMI backends
Amazon SageMaker AI
High throughput, batching, autoscaling, production GPU serving
Any containerized stack
Your preferred runtime
Amazon EKS or Amazon ECS
Inference must integrate into an existing container framework
Each deployment pattern in this post follows the same general workflow:
- Fine-tune or download a model in Unsloth.
- Export the model file that matches the runtime you want.
- Validate the runtime locally or on Amazon EC2.
- Promote the same model file and runtime combination to a managed or environment-native deployment.
That sequencing helps avoid unexpected behavior later, especially around memory use, prompt formatting, and latency behavior.
Pattern 1: GGUF on Amazon EC2 with llama.cpp and Unsloth
Use this pattern to validate quantization levels quickly with direct instance access. For many use cases, Amazon EC2 is a strong starting point because you get maximum control with minimum abstraction. Benchmark several quantization levels, test prompt formatting, compare CPU versus GPU behavior, and understand the actual memory footprint before you commit to a managed endpoint design.
A typical Unsloth export looks like this:
model.save_pretrained_gguf("gguf_model", tokenizer, quantization_method="q4_k_xl")This produces a GGUF file ready for local llama.cpp-based inference. The companion repository uses q4_k_xl for its quantized endpoint. Different quantization methods control the trade-off between file size and output fidelity: use q8_0 for higher output fidelity at roughly double the file size, or f16 for a full-precision GGUF with no quantization loss. See the Unsloth GGUF documentation for the complete list of quantization methods and their characteristics.
After you have the GGUF, a minimal llama-server launch requires the following configurations:
llama-server \
--model /models/my-model.gguf \
--alias my-model \
--ctx-size 8192 \
--host 0.0.0.0 \
--port 8080unsloth run \
--model /models/my-model.gguf \
--alias my-model \
--ctx-size 8192 \
--host 0.0.0.0 \
--port 8080At that point, your application can talk to the model through an OpenAI-compatible interface:
from openai import OpenAI
client = OpenAI(
base_url="http://:8080/v1",
api_key="not-required",
)
response = client.chat.completions.create(
model="my-model",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain AWS Graviton in two sentences."},
],
max_tokens=128,
)
print(response.choices[0].message.content)Important: This configuration is suitable for isolated testing. For production, restrict the security group to known Classless Inter-Domain Routing (CIDR) blocks, bind to a private interface (for example, 127.0.0.1), and place the endpoint behind an authenticated API gateway or load balancer.
This path is attractive for three reasons. It is transparent to debug, it stays close to upstream runtime behavior, and it gives you a clean place to test quantization choices before you add container contracts, autoscaling policies, or endpoint governance.
Amazon EC2 is also the most direct place to evaluate practical deployment questions:
- Quantization quality – Compare outputs across quantization levels (for example, q4_k_m versus q8_0) against your specific evaluation criteria. Quality impact varies by model architecture and task.
- Hardware requirements – If the model’s memory footprint exceeds available CPU RAM, you need a GPU-backed instance. Check peak memory usage during inference, not only model load. For best performance, have sufficient RAM or VRAM to load the entire model into memory. For example, if the model is 128 GB disk, aim for more than 128 GB of available RAM or VRAM.
- Context length trade-offs – Longer context windows increase both latency and memory consumption. Test with representative prompt lengths to find the right balance for your workload.
- Chat template validation – Verify that the structured prompt format (which maps roles such as “system” and “user” to the token sequences the model expects) produces consistent behavior outside the training environment.
For evaluation, internal tools, proof-of-concept work, and early production pilots, Amazon EC2 is often the right starting point.
Pattern 2: GGUF on Amazon SageMaker AI with a custom container
Amazon EC2 is recommended for fast iteration, but it doesn’t give you a managed inference service out of the box. When you want a production endpoint with autoscaling, monitoring, AWS Identity and Access Management (IAM) integration, and a stable API surface, Amazon SageMaker AI inference endpoints become the better fit.
For GGUF deployments, the most practical design is usually a custom inference container that packages the GGUF model file together with llama.cpp or another lightweight runtime. The container then exposes the Amazon SageMaker AI hosting interface, which requires that the container listen on port 8080, implement /ping for health checks, and /invocations for inference requests.
The companion GitHub repository includes a complete working example of this pattern. It deploys a side-by-side comparison of Unsloth’s dynamically quantized Qwen3-VL-8B-Instruct (Q4_K_XL GGUF served with llama.cpp on ml.g5.xlarge, approximately $1.41/hr) against the full-precision BF16 variant (served with vLLM on ml.g5.12xlarge, approximately $7.09/hr). Pricing as of June 2026; see the Amazon SageMaker AI pricing page for current rates. The entrypoint script starts llama-server on an internal port and uses nginx as a reverse proxy to satisfy the Amazon SageMaker AI interface:
# Start llama-server with the GGUF model and vision projector
/app/llama-server \
--model /models/Qwen3-VL-8B-Instruct-UD-Q4_K_XL.gguf \
--mmproj /models/mmproj-F16.gguf \
--host 0.0.0.0 \
--port 8081 \
--ctx-size 4096Nginx then maps /ping to the llama-server health check and /invocations to the chat completions endpoint, giving Amazon SageMaker AI a standard interface while keeping the runtime lightweight:
# SageMaker health check endpoint
location /ping {
proxy_pass http://llama_backend/health;
}
# SageMaker inference endpoint -> llama.cpp chat completions
location /invocations {
proxy_pass http://llama_backend/v1/chat/completions;
proxy_read_timeout 120s;
}A common architecture might look like this:
- Store the finalized GGUF model file in Amazon Simple Storage Service (Amazon S3).
- Start the Amazon SageMaker AI container and place the model under /opt/ml/model.
- Launch llama.cpp or Unsloth against the local model file.
- Expose a thin API layer that translates Amazon SageMaker AI requests into local inference calls.
The following architecture diagram from the companion GitHub repository shows how the sample deploys both a quantized GGUF endpoint (this pattern) and a full-precision vLLM endpoint (Pattern 3). The flow works as follows:

*Figure: Architecture diagram of the companion sample deployment.*
- Terraform provisions all infrastructure including Amazon Elastic Container Registry (Amazon ECR), AWS CodeBuild, and Amazon S3 resources.
- AWS CodeBuild builds the custom container image and pushes it to Amazon ECR.
- Amazon SageMaker AI creates two real-time endpoints within a virtual private cloud (VPC): one for the quantized GGUF model (Pattern 2) and one for the full-precision model (Pattern 3).
- Both endpoints pull their respective model files from Amazon S3 at startup.
- An Amazon SageMaker Notebook Instance provides access to the comparison notebook for running evaluations against both endpoints.
This pattern works well because it keeps the runtime lightweight while letting Amazon SageMaker AI handle the operational concerns that matter in production, such as endpoint lifecycle and autoscaling. For smaller models, this path is especially compelling on CPU-backed endpoints. For larger quantized models or lower-latency requirements, you can move the same design to GPU-backed endpoints.
A trade-off is that llama.cpp is the inference/deployment engine, but not the whole serving system. In Amazon SageMaker AI, you still need a container that behaves like an Amazon SageMaker AI endpoint. That wrapper layer does not require significant implementation effort, but it’s an important part of the production design.
Pattern 3: Merged weights on Amazon SageMaker AI with GPU-optimized serving engines
GGUF is excellent when model file size and lightweight serving are the priorities. It’s not always the right choice when you prioritize throughput and GPU efficiency. Merged weights become more attractive in those scenarios.
Merged weights refer to a model saved as a single unified set of safetensors weights. This is often the result of combining a fine-tuned adapter (such as a Low-Rank Adaptation (LoRA), adapter) with the base model, but it also applies to base models saved directly in a deployment-ready format. Unsloth supports save paths for merged 16-bit and merged 4-bit outputs, along with LoRA-only exports. Those are more aligned with runtimes such as vLLM and SGLang that are built around production GPU serving patterns such as batching, high token throughput, and multi-GPU scaling.
A representative export looks like this:
model.save_pretrained_merged(
"finetuned_model",
tokenizer,
save_method="merged_16bit",
)The serving path is:
vllm serve finetuned_modelOn AWS, the LMI containers available for Amazon SageMaker AI are especially relevant here. For the full-precision endpoint in the companion sample, the LMI container for Amazon SageMaker AI is configured entirely through environment variables on the Terraform model resource:
HF_MODEL_ID = "Qwen/Qwen3-VL-8B-Instruct"
OPTION_DTYPE = "bf16"
OPTION_ROLLING_BATCH = "vllm"
OPTION_TENSOR_PARALLEL_DEGREE = "4"
OPTION_MAX_MODEL_LEN = "4096"No custom container is needed. The LMI container downloads the model from <a href="https://huggingface.co/Qwen/Qwen3-VL-8B-Instruct" target="_blank
関連記事
今日のまとめ
AI日報で今日の重要ニュースをまとめ読み