Amazon SageMaker AI における EU AI 法対応のガイドライン
AWS は EU AI Act の遵守要件に対応するため、Amazon SageMaker AI で大規模言語モデルのファインチューニング時に FLOPs を自動計測・追跡する機能を導入し、規制リスクを管理する手段を提供した。
キーポイント
EU AI Act のコンプライアンス要件と FLOPs
2025 年 8 月 2 日に施行される EU AI Act では、LLM のファインチューニングにおいて計算資源(FLOPs)の計測が義務付けられ、使用量が元のモデルの 1/3 を超えると「下流ユーザー」から「一般目的 AI モデルプロバイダ」として再分類され、厳格な規制対象となる。
SageMaker AI の FLOPs Meter ツール
AWS は既存の SageMaker パイプラインに統合可能なオープンソースの「Fine-Tuning FLOPs Meter」ツールキットを提供し、単一の設定フラグでコンプライアンスステータスを判定・追跡できるようにした。
監査対応とガバナンス機能
AWS CloudTrail や Amazon CloudWatch と連携し、トレーニング完了後のリソース自動廃止や監査証跡の生成を自動化することで、組織が規制要件を満たすためのドキュメント作成を容易にする。
FLOPsメーターの自動計測機能
Hugging Face TrainerCallbackとして実装されたFLOPs Meterは、レシピYAMLにcompute_flops: trueを追加するだけでトレーニング中に自動的に計算を開始します。
カスタムトレーナーによるトークンカウント
標準のSFTTrainerではなく、各トレーニングステップでパディングを除いたトークンを正確に数えるためにTokenCountingSFTTrainerが使用されます。
EU AI Act 準拠の FLOPs 計測パイプライン
トレーニング完了時に分析値とハードウェア値を計算し、SageMaker の出力ディレクトリに JSON ファイルとして保存後、S3 と DynamoDB にアップロードして監査証跡を残します。
事前推定ツールの活用
LoRA やフルファインチューニングなど異なる手法の FLOPs を事前に比較できるユーティリティがあり、コンプライアンス閾値に近いかを計画段階で判断できます。
影響分析・編集コメントを表示
影響分析
この発表は、EU AI Act の施行を控える中で、特に大規模モデルを扱う企業にとって極めて重要なコンプライアンス対策ツールを提供するものです。AWS が規制要件を技術的な実装(FLOPs メーター)としてパッケージ化することで、企業が手動で計算コストを追跡する負担を減らし、法的リスクを最小化する道筋を示しています。
編集コメント
EU の規制強化に伴い、クラウドプロバイダーがコンプライアンス要件をインフラレベルで実装する動きは加速しており、AWS のこの対応は業界標準となりつつある重要なステップです。
EU AI 法は、大規模言語モデル(LLM)のファインチューニングを行う組織に対し、浮動小数点演算数(FLOPs)で測定される計算リソースを追跡し、規制遵守義務を判断することを要求しています。顧客がドメイン固有の使用ケース向けに LLM のファインチューニングを日益増している中、「トレーニングジョブが新たな規制義務を発動させるかどうかをどうやって知ればよいのか」という共通の質問をよく耳にします。
Amazon SageMaker AI は、モデルの構築、トレーニング、デプロイを行うマネージド型機械学習(ML)サービスです。このソリューションは、完全マネージドなインフラ上でファインチューニングワークロードを実行するために Amazon SageMaker Training ジョブを利用します。SageMaker Training ジョブは、リソースのプロビジョニング、スケーリング、クラスター管理を担い、分散トレーニングのネイティブサポート、ガバナンスのための AWS CloudTrail および Amazon CloudWatch との統合、トレーニング完了後の計算リソースの自動廃止機能を備えています。Fine-Tuning FLOPs Meter は、既存の SageMaker AI パイプラインに組み込まれる目的特化型のコンプライアンス追跡機能により、これらの能力を拡張します。
本記事では、Amazon SageMaker AI 上でオープンソースの Fine-Tuning FLOPs Meter ツールキット を使用して、大規模言語モデル(LLM)のファインチューニング中に FLOPs(1 秒あたりの浮動小数点演算回数)を追跡する方法をご紹介します。単一の設定フラグでコンプライアンスステータスを判定し、監査対応可能なドキュメントを生成する手順も解説します。
EU AI Act および FLOPs 追跡要件
2025 年 8 月 2 日、EU AI 法(欧州連合人工知能法)は、一般目的型人工知能(GPAI: General-Purpose Artificial Intelligence)モデルを扱う組織に対して 新たな要件 を導入しました。LLM のファインチューニングを行っている場合、その変更によって、既存のモデルを実質的な改変なしに使用する「下流ユーザー」から、モデルのコンプライアンスに対して法的責任を負う「GPAI モデルプロバイダー」へと再分類されるかどうかを判断する必要があります。この分類は、FLOPs(1 秒あたりの浮動小数点演算回数)で測定されたファインチューニングにおける計算リソースの使用量に依存します。
3 分の 1 ルールは、軽微な修正と大規模な再学習を区別するものです。この 30% の閾値の背後にある理由:規制分析では、元のトレーニング計算量の 3 分の 1 を超えて使用すると、モデルに著しい行動変化が生じ、実質的に異なるリスクを持つ新しいモデルが作成されるため、完全なプロバイダー義務の対象となると判断されています。ほとんどの組織は以下の表のシナリオ 2 を使用します。これは、モデルプロバイダーが正確なトレーニング FLOPs(浮動小数点演算数)を公開することが稀だからです。モデルプロバイダーから文書化された事前学習計算量が入手できない場合、デフォルト閾値である 3.3×10²² FLOPs が適用されます。考慮すべき適用可能なシナリオと閾値は以下の 3 つあります。
シナリオ
閾値
事前学習計算量が既知で ≥ 10²³ FLOPs の場合
実際の事前学習計算量の 30%
事前学習計算量が不明な場合
デフォルト閾値の 3.3×10²² FLOPs
システムリスクモデル(事前学習 FLOPs ≥ 10²⁵ FLOPs の場合)
ベース計算量が不明な場合は 3.3×10²⁴ FLOPs
Fine-Tuning FLOPs メーターは、PRETRAIN_FLOPS 環境変数を指定したかどうかに基づいて、どのシナリオが適用されるかを自動的に判断します。どの閾値パスが適用されるかを素早く特定するために、以下の意思決定フローを使用してください。
ステップ 1:ベースモデルの事前学習 FLOPs をご存知ですか?
- いいえ:3.3×10²² FLOPs のデフォルト閾値に直接進んでください。
- はい:次の評価ステップへ進みます。
ステップ 2: プリートレーニング計算規模の評価
プリートレーニングの計算量が既知の場合、以下の桁数と比較してください。
- プリートレーニング計算量は ≥ 10²⁵ FLOPs か?
はい:あなたはシステムリスク閾値に該当します。3.3×10²⁴ FLOPs の閾値を使用してください。
- いいえ:次の質問へ進みます。
- プリートレーニング計算量は ≥ 10²³ FLOPs か?
はい:実際のプリートレーニング計算量の 30% を相対閾値として使用してください。
- いいえ:3.3×10²² FLOPs のデフォルト閾値へ進んでください。
例えば、Llama-3-70B(推定最小 1.5×10²⁴ FLOPs でプリートレーニング済み)をファインチューニングする場合、閾値は 4.5×10²³ FLOPs となります。この閾値を超えると、一般目的人工知能(GPAI: General Purpose AI)モデルプロバイダーとしての完全な義務を負うことになります。これらの義務には、詳細なアーキテクチャおよびトレーニングプロセスの開示、使用したデータソースの公開リストの提供、EU 著作権法への準拠の実証が含まれます。これに違反した場合、1,500 ユーロまたはグローバル年間売上の 3% のいずれか高い方の金額までの罰金科される可能性があります。
手動 FLOPs 追跡の課題
これらの閾値は、以下の 3 つのコンプライアンス課題を提示します。
- FLOPs(浮動小数点演算回数)の計算式は複雑であり、フルファインチューニングを行うか、パラメータ効率的な手法(Low-Rank Adaptation (LoRA) のようにモデルのパラメータのごく一部のみを更新するトレーニングアプローチなど)を使用するかによって異なります。
- 適用される閾値を決定するのは困難です。なぜなら、事前学習における計算リソースの数はほとんど公開されていないからです。
- 複数のトレーニングジョブにわたって監査証跡(規制レビューのためのコンプライアンス指標の恒久的な記録)を維持することは、運用上のオーバーヘッドを増加させます。
誤った計算は、あなたが下流ユーザーとして運営するか、それとも完全な GPAI モデルプロバイダーとして分類されるかを決定づけます。Fine-Tuning FLOPs Meter はこれらの課題に対処し、追跡プロセスを自動化します。
ソリューションの概要
Fine-Tuning FLOPs Meter は、Amazon SageMaker Generative AI レシピリポジトリで入手可能なオープンソースツールキットであり、Amazon SageMaker AI 上の Hugging Face トレーニングワークフローに統合されます。これはファインチューニングのライフサイクル全体にわたって計算リソースを追跡します。以下の図はコンプライアンスワークフローを示しています。
image
図 1. Fine-Tuning FLOPs Meter のコンプライアンスワークフロー
このツールキットは、ファインチューニングのライフサイクルにおける3つの段階をカバーしており、その中核機能としてランタイム追跡が含まれています。
第一段階: オプションの事前トレーニング推定ユーティリティにより、ジョブを実行する前に、LoRA、Spectrum、フルといった各トレーニング手法間で予想されるFLOPs(浮動小数点演算数)を比較することができます。
第二段階: 本機能であるランタイム追跡では、Hugging Face の TrainerCallback を使用して、アーキテクチャベースの分析と NVIDIA Management Library (NVML) を通じたハードウェアベースの GPU モニタリングの両方を用いながら、トレーニング中に FLOPs をリアルタイムで計算します。
第三段階: トレーニング後の監査証跡が自動的に、完全なコンプライアンス指標を JSON 形式で保存します。結果は Amazon Simple Storage Service (Amazon S3) または Amazon DynamoDB に永続化できます。
設定行に compute_flops: true を追加するだけで利用を開始できます。FLOPs メーターには、フル、LoRA、Spectrum の各ファインチューニング手法を正確に見積もるための改良された数式を用いたパラメータ効率性の認識機能が組み込まれています。これは EU AI 法(EU Artificial Intelligence Act)の報告に必要な項目を網羅した監査対応可能なコンプライアンス文書を生成し、適用される規制閾値を特定するのに役立つ自動的な閾値比較を実行して、ファインチューニングジョブがそれを超過しているかどうかをフラグ付けします。
技術的実装
以下の各サブセクションでは、FLOPs の計算方法と、この追跡機能が Amazon SageMaker AI 上のトレーニングワークフローにどのように統合されるかについて解説します。
前提条件
FLOPs メーターのウォークスルーを実行する前に、以下の前提条件を完了する必要があります:
- SageMaker AI に対して、以下のクォータ増分リクエストを行ってください。このユースケースでは、最小限として ml.g5.4xlarge インスタンス(NVIDIA A10G GPU を 1 基搭載)が必要です。Service Quotas コンソールで、トレーニングジョブの使用目的に SageMaker AI の G5 インスタンス (ml.g5.4xlarge) のクォータをリクエストしてください:1
- 必要なアクセス権限を SageMaker AI に付与して例を実行できるようにするため、管理ポリシーとして AmazonSageMakerFullAccess と AmazonS3FullAccess を持つ AWS Identity and Access Management (IAM) ロールを作成してください。
- 以下のポリシーを IAM ロールの信頼関係として割り当ててください:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": [
"sagemaker.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}
- (オプション)前述のロールを使用して Jupyter ノートブックにアクセスできるようにするため、Amazon SageMaker Studio ドメインを作成してください(Amazon SageMaker AI のクイックセットアップに関するドキュメントを参照)。ローカル環境で JupyterLab を使用することも可能です。
これらの権限は広範なアクセス権を与えますが、本番環境での利用は推奨されません。より細粒度の権限を定義する方法については、SageMaker AI 開発者ガイド を参照してください。
FLOPs 計算式
コンプライアンス報告には、主要指標として解析手法(Flops_architecture)を使用してください。本ツールキットは、保守的な報告のためにハードウェアベースの上限値も同時に算出します。両方の方法は自動的に実行されます。以下のセクションで実装の詳細を説明します。
EU AI Act のガイドライン(セクション A.2.1)では、トレーニング計算量の推定に関する 2 つのアプローチが記述されています:
- アーキテクチャベースのアプローチ(解析的):
密なトランスフォーマーに対する標準的な EU 式は以下の通りです。
C ≈ 6 × P × D
ここで、P はパラメータ数、D はトレーニングトークン数を表します。これは全パラメータが学習可能である完全ファインチューニングを前提としています。
パラメータ効率化手法を考慮した拡張式は以下の通りです。
F_ft = (4 × N_total + 2 × N_trainable) × tokens_processed
内訳は以下の通りです:
- 4 × N_total — 各層(凍結された層を含む)における順伝播(2 倍)と逆伝播の勾配計算(2 倍)
- 2 × N_trainable — 学習可能な重みに関する勾配計算のみ
完全ファインチューニングでは N_total = N_trainable となるため、これは 6 × N × D に簡略化され、EU 式と等価になります。LoRA や Spectrum の場合、より少ないパラメータに勾配更新が行われることを反映し、より正確(かつ低い)な推定値を提供します。
- ハードウェアベースのアプローチ(上限値):
このアプローチでは以下の式を使用します。
C = N_gpus × L × H × U
ここで、N_gpus は GPU の数、L は秒単位のトレーニング期間、H はピーク理論性能(FLOPs)、U は利用率を表します。FLOPs メーターは、NVML GPU モニタリングを通じて保守的な上限値を算出するために *U = 1.0*(100% 利用率)を使用します。
スレッショルドロジック
このツールキットは、determine_compliance_threshold() 関数において EU AI Act のスレッショルドロジックを実装しています:
EU_AI_ACT_GPAI_THRESHOLD = 1e23 # 10²³ FLOPs
EU_AI_ACT_DEFAULT_THRESHOLD = 3.3e22 # 10²³の 3 分の 1
if pretrain_flops is None or pretrain_flops
SageMaker トレーニングジョブとの統合
FLOPs メーターは、Hugging Face TrainerCallback として機能します。追跡を有効にするには、レシピ YAML に以下の一行を追加してください:
compute_flops: true
トレーニング起動時、トレーニングスクリプト(sft.py)はこのフラグを確認し、有効化されていれば、モデルのパラメータ数と任意の PRETRAIN_FLOPS 環境変数を指定して FlopsMeterCallback を初期化します。また、各トレーニングステップでパディングされていないトークンをカウントするために、カスタムの TokenCountingSFTTrainer が標準の SFTTrainer に置き換えられます。
n_total = sum(p.numel() for p in model.parameters())
n_trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
flops_cb = FlopsMeterCallback(
pad_token_id=tokenizer.pad_token_id,
pretrain_flops=pretrain_flops, # from PRETRAIN_FLOPS env var
sample_nvml=True,
n_total=n_total,
n_trainable=n_trainable,
model_name=model_args.model_name_or_path,
num_epochs=training_args.num_train_epochs,
)
At training completion, the callback computes both analytical and hardware FLOPs, determines the applicable threshold, and writes a flops_meter.json file to /opt/ml/output/. The pipeline's ProcessTrainingOutputs step then uploads the results to Amazon S3 and persists them to Amazon DynamoDB for audit trail purposes.
Walkthrough
The following walkthrough uses meta-llama/Llama-3.2-3B-Instruct (3.21 billion parameters). Because Meta has not published exact pretraining FLOPs for this model, the default threshold path applies: 3.3×10²² as the compliance threshold.
Pre-Training estimation (optional)
A standalone estimation utility (estimate_flops.py) compares expected FLOPs across training methods (LoRA, Spectrum, and full fine-tuning) before you launch a job. This is useful for planning: it shows how close a given configuration comes to the compliance threshold, helping you make informed decisions about training method and dataset size. The estimation utility is separate from the core runtime tracking and you can run it independently in a notebook.
ランタイム追跡
トレーニング中、FlopsMeterCallback は FLOPs をリアルタイムで追跡します。これが実際のコンプライアンス測定が行われる場所です。トレーニングが開始されると(on_train_begin)、このコールバックはモデルのパラメータ数(N_total, N_trainable)をキャプチャし、NVML GPU 監視スレッドを開始して、開始時刻のタイムスタンプを記録します。トレーニングが進むにつれて、非パディングトークンが各サブステップでバッチごとにカウントされ(on_substep_end)、分散トレーニングでは GPU 間で集約されます。トレーニングが完了すると(on_train_end)、コールバックは蓄積されたトークン数からアーキテクチャベースの FLOPs を計算し、ハードウェア上限値を算出するために NVML 監視を停止し、適用される閾値を決定して、完全なメトリクスを flops_meter.json に書き込みます。
LoRA と FLOPs 追跡を有効にした Llama-3.2-3B のレシピ設定:
model_name_or_path: meta-llama/Llama-3.2-3B-Instruct
dataset_id_or_path: your-dataset.jsonl
use_peft: true
compute_flops: true
per_device_train_batch_size: 8
num_train_epochs: 10
learning_rate: 2e-5
peft_config:
r: 8
lora_alpha: 16
target_modules: ["q_proj", "v_proj"]
Amazon SageMaker AI のノートブックまたは Python スクリプトでは、SageMaker Python SDK v3 から ModelTrainer クラスを使用して、トレーニングジョブを SageMaker Training job として起動します:
from sagemaker.modules.configs import Compute, SourceCode
from sagemaker.modules.train import ModelTrainer
training_instance_type = "ml.g5.4xlarge"
pytorch_image_uri = sagemaker.image_uris.retrieve(
framework="pytorch",
region=sess.boto_session.region_name,
version="2.7.1",
instance_type=training_instance_type,
image_scope="training",
)
source_code = SourceCode(
source_dir="./sagemaker_code",
command="bash sm_accelerate_train.sh --config hf_recipes/meta-llama/Llama-3.2-3B-Instruct--vanilla-peft-qlora.yaml",
)
compute = Compute(
instance_type=training_instance_type,
instance_count=1,
volume_size_in_gb=300,
)
model_trainer = ModelTrainer(
training_image=pytorch_image_uri,
source_code=source_code,
compute=compute,
role=role,
environment={
"FLOPS_METER_NVML": "1",
},
)
model_trainer.train()
このモデルの事前学習における FLOPs(浮動小数点演算数)は不明であるため、PRETRAIN_FLOPS 環境変数は省略されています。デフォルトの閾値が自動的に適用されます。
コンプライアンス文書
トレーニング完了時に、コールバックにより n というメトリクスを含む flops_meter.json ファイルが生成されます。
原文を表示
The EU AI Act requires organizations fine-tuning large language models (LLMs) to track computational resources measured in floating-point operations (FLOPs) to determine compliance obligations. As customers increasingly fine-tune LLMs for domain-specific use cases, we hear a common question: how do I know if my training job triggers new regulatory obligations?
Amazon SageMaker AI provides a managed machine learning (ML) service for building, training, and deploying models. This solution uses Amazon SageMaker Training jobs to run fine-tuning workloads on fully managed infrastructure. SageMaker Training jobs handle resource provisioning, scaling, and cluster management, with built-in support for distributed training, integration with AWS CloudTrail and Amazon CloudWatch for governance, and automatic decommissioning of compute resources after training completes. The Fine-Tuning FLOPs Meter extends these capabilities with purpose-built compliance tracking that integrates into your existing SageMaker AI pipelines.
In this post, we show you how to set up FLOPs tracking during LLM fine-tuning using the open source Fine-Tuning FLOPs Meter toolkit on Amazon SageMaker AI. You learn how to determine your compliance status with a single configuration flag and generate audit-ready documentation.
EU AI Act and FLOPs tracking requirements
On August 2, 2025, the EU AI Act introduced new requirements for organizations working with general-purpose artificial intelligence (GPAI) models. If you’re fine-tuning an LLM, you must determine whether your modifications reclassify you from a downstream user (an organization that uses an existing model without substantial modification) to a GPAI model provider (an organization legally responsible for a model’s compliance). The classification depends on how much compute your fine-tuning consumes, measured in FLOPs.
The one-third rule distinguishes between minor modifications and substantial retraining. The rationale behind the 30% threshold: regulatory analysis determined that using more than one-third of the original training compute typically results in significant behavioral changes to the model, effectively creating a new model with different risks that warrant full provider obligations. Most organizations use scenario 2 in the following table because model providers rarely publish exact training FLOPs. Unless you have documented pretraining compute from your model provider, the default threshold of 3.3×10²² FLOPs applies. There are 3 applicable scenarios and thresholds to consider:
Scenario
Threshold
Pretraining compute is known and ≥ 10²³ FLOPs
30% of the actual pretraining compute
Pretraining compute is unknown or
Default threshold of 3.3×10²² FLOPs
Systemic Risk Models (Pre-training FLOPs ≥ 1025 FLOPs)
3.3×1024 FLOPs (if base compute is unknown)
The Fine-Tuning FLOPs Meter automatically determines which scenario applies based on whether you provide the PRETRAIN_FLOPS environment variable. To help you quickly determine which threshold path applies, use the following decision flow:
Step 1: Do you know your base model’s pretraining FLOPs?
- No: Proceed directly to the Default Threshold of 3.3×10²² FLOPs.
- Yes: Move to the next evaluation step.
Step 2: Evaluate pretraining compute scale
If you know your pretraining compute, compare it against the following orders of magnitude:
- Is pretraining compute ≥ 1025 FLOPs?
Yes: You fall under the Systemic Risk Threshold. Use a threshold of 3.3×1024 FLOPs.
- No: Move to the next question.
- Is pretraining compute ≥ 10²³ FLOPs?
Yes: Use a Relative Threshold of 30% of actual pretraining compute.
- No: Proceed to the Default Threshold of 3.3×10²² FLOPs.
For example, fine-tuning Llama-3-70B (pretrained with an estimated minimum of 1.5×10²⁴ FLOPs) sets the threshold at 4.5×10²³ FLOPs. Exceeding this threshold means you take on the full obligations of a GPAI model provider. Those obligations include delivering detailed architecture and training process disclosures, providing a public-facing list of data sources used, and demonstrating compliance with EU copyright law. If you don’t comply, you might face fines up to €15 million or 3% of your global annual turnover, whichever is higher.
The challenge of manual FLOPs tracking
These thresholds present three compliance challenges:
- FLOPs formulas are complex and differ depending on whether you’re doing full fine-tuning or using parameter-efficient methods (training approaches like Low-Rank Adaptation (LoRA) that update only a small subset of model parameters).
- The applicable threshold is hard to determine because pretraining compute figures are rarely published.
- Maintaining an audit trail (a permanent record of compliance metrics for regulatory review) across multiple training jobs adds operational overhead.
Incorrect calculations change whether you operate as a downstream user or face classification as a full GPAI model provider. The Fine-Tuning FLOPs Meter automates the tracking process, addressing these challenges.
Solution overview
The Fine-Tuning FLOPs Meter is an open source toolkit, available in the Amazon SageMaker Generative AI recipes repository, that integrates into Hugging Face training workflows on Amazon SageMaker AI. It tracks computational resources across the entire fine-tuning lifecycle. The following diagram illustrates the compliance workflow.

Figure 1. Fine-Tuning FLOPs Meter compliance workflow
The toolkit covers three stages of the fine-tuning lifecycle, with runtime tracking as the core capability.
First stage: an optional pre-training estimation utility lets you compare expected FLOPs across training methods (LoRA, Spectrum, Full) before you launch a job.
Second stage: runtime tracking, the main feature, uses a Hugging Face TrainerCallback to calculate FLOPs in real time during training using both architecture-based analytics and hardware-based GPU monitoring through NVIDIA Management Library (NVML).
Third stage: a post-training audit trail automatically stores complete compliance metrics in JSON format. You can persist results to Amazon Simple Storage Service (Amazon S3) or Amazon DynamoDB.
You can opt in with a single configuration line (compute_flops: true). The FLOPs Meter includes parameter-efficient awareness using an enhanced formula to accurately estimate for full, LoRA, and Spectrum fine-tuning approaches. It generates audit-ready compliance documentation covering the fields required for EU AI Act reporting, and it performs automated threshold comparison that helps determine the applicable regulatory threshold and flags whether your fine-tuning job exceeds it.
Technical implementation
The following subsections cover how FLOPs are calculated and how the tracking integrates with your training workflow on Amazon SageMaker AI.
Prerequisites
You must complete the following prerequisites before you can run the FLOPs Meter walkthrough:
- Make the following quota increase request for SageMaker AI. For this use case, you need a minimum of 1 ml.g5.4xlarge instance (with 1 x NVIDIA A10G GPU). On the Service Quotas console, request the SageMaker AI quota G5 instances (ml.g5.4xlarge) for training job usage: 1
- Create an AWS Identity and Access Management (IAM) role with managed policies AmazonSageMakerFullAccess and AmazonS3FullAccess to give required access to SageMaker AI to run the examples.
- Assign the following policy as a trust relationship to your IAM role:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": [
"sagemaker.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}
- (Optional) Create an Amazon SageMaker Studio domain (refer to Use quick setup for Amazon SageMaker AI) to access Jupyter notebooks with the preceding role. You can also use JupyterLab in your local setup.
These permissions grant broad access and are not recommended for use in production environments. For guidance on defining more fine-grained permissions, refer to the SageMaker AI Developer Guide.
FLOPs calculation formulas
For compliance reporting, use the analytical method (Flops_architecture) as your primary metric. The toolkit also calculates a hardware-based upper bound for conservative reporting. Both methods run automatically. The following sections describe the implementation details.
The EU AI Act guidelines (Section A.2.1) describe two approaches for estimating training compute:
- Architecture-based approach (analytical):
The standard EU formula for dense transformers is:
C ≈ 6 × P × D
Where P is the number of parameters and D is the number of training tokens. This assumes full fine-tuning, where all parameters are trainable.
An enhanced formula accounts for parameter-efficient methods:
F_ft = (4 × N_total + 2 × N_trainable) × tokens_processed
Here’s the breakdown:
- 4 × N_total — forward pass (2×) plus backward pass gradient computation through each layer (2×), including frozen ones
- 2 × N_trainable — gradient computation with respect to trainable weights only
For full fine-tuning where N_total = N_trainable, this reduces to 6 × N × D, which is equivalent to the EU formula. For LoRA or Spectrum, it provides a more accurate (and lower) estimate, reflecting that fewer parameters receive gradient updates.
- Hardware-based approach (upper bound):
This approach uses the following formula:
C = N_gpus × L × H × U
Where N_gpus is the number of GPUs, L is training duration in seconds, H is peak theoretical performance (FLOPs), and U is utilization. The FLOPs Meter uses *U = 1.0* (100% utilization) to produce a conservative upper bound via NVML GPU monitoring.
Threshold logic
The toolkit implements the EU AI Act threshold logic in determine_compliance_threshold():
EU_AI_ACT_GPAI_THRESHOLD = 1e23 # 10²³ FLOPs
EU_AI_ACT_DEFAULT_THRESHOLD = 3.3e22 # One-third of 10²³
if pretrain_flops is None or pretrain_flops < EU_AI_ACT_GPAI_THRESHOLD:
threshold = EU_AI_ACT_DEFAULT_THRESHOLD # "default_3.3e22"
else:
threshold = 0.30 * pretrain_flops # "30pct_of_actual_pretraining"
Integration with SageMaker Training jobs
The FLOPs Meter works as a Hugging Face TrainerCallback. To activate tracking, add a single line in the recipe YAML:
compute_flops: true
At training launch, the training script (sft.py) checks this flag and, if activated, initializes the FlopsMeterCallback with model parameter counts and an optional PRETRAIN_FLOPS environment variable. A custom TokenCountingSFTTrainer replaces the standard SFTTrainer to count non-padding tokens at each training step.
n_total = sum(p.numel() for p in model.parameters())
n_trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
flops_cb = FlopsMeterCallback(
pad_token_id=tokenizer.pad_token_id,
pretrain_flops=pretrain_flops, # from PRETRAIN_FLOPS env var
sample_nvml=True,
n_total=n_total,
n_trainable=n_trainable,
model_name=model_args.model_name_or_path,
num_epochs=training_args.num_train_epochs,
)
At training completion, the callback computes both analytical and hardware FLOPs, determines the applicable threshold, and writes a flops_meter.json file to /opt/ml/output/. The pipeline’s ProcessTrainingOutputs step then uploads the results to Amazon S3 and persists them to Amazon DynamoDB for audit trail purposes.
Walkthrough
The following walkthrough uses meta-llama/Llama-3.2-3B-Instruct (3.21 billion parameters). Because Meta has not published exact pretraining FLOPs for this model, the default threshold path applies: 3.3×10²² as the compliance threshold.
Pre-Training estimation (optional)
A standalone estimation utility (estimate_flops.py) compares expected FLOPs across training methods (LoRA, Spectrum, and full fine-tuning) before you launch a job. This is useful for planning: it shows how close a given configuration comes to the compliance threshold, helping you make informed decisions about training method and dataset size. The estimation utility is separate from the core runtime tracking and you can run it independently in a notebook.
Runtime tracking
During training, the FlopsMeterCallback tracks FLOPs in real time. This is where the actual compliance measurement happens. When training begins (on_train_begin), the callback captures model parameter counts (N_total, N_trainable), starts an NVML GPU monitoring thread, and records the start timestamp. As training progresses, non-padding tokens are counted per batch at each substep (on_substep_end) and aggregated across GPUs in distributed training. When training completes (on_train_end), the callback computes architecture-based FLOPs from the accumulated token count, stops NVML monitoring to calculate the hardware upper bound, determines the applicable threshold, and writes the complete metrics to flops_meter.json.
A recipe configuration for Llama-3.2-3B with LoRA and FLOPs tracking activated:
model_name_or_path: meta-llama/Llama-3.2-3B-Instruct
dataset_id_or_path: your-dataset.jsonl
use_peft: true
compute_flops: true
per_device_train_batch_size: 8
num_train_epochs: 10
learning_rate: 2e-5
peft_config:
r: 8
lora_alpha: 16
target_modules: ["q_proj", "v_proj"]
In your Amazon SageMaker AI notebook or Python script, use the ModelTrainer class from the SageMaker Python SDK v3 to launch the training job as a SageMaker Training job:
from sagemaker.modules.configs import Compute, SourceCode
from sagemaker.modules.train import ModelTrainer
training_instance_type = "ml.g5.4xlarge"
pytorch_image_uri = sagemaker.image_uris.retrieve(
framework="pytorch",
region=sess.boto_session.region_name,
version="2.7.1",
instance_type=training_instance_type,
image_scope="training",
)
source_code = SourceCode(
source_dir="./sagemaker_code",
command="bash sm_accelerate_train.sh --config hf_recipes/meta-llama/Llama-3.2-3B-Instruct--vanilla-peft-qlora.yaml",
)
compute = Compute(
instance_type=training_instance_type,
instance_count=1,
volume_size_in_gb=300,
)
model_trainer = ModelTrainer(
training_image=pytorch_image_uri,
source_code=source_code,
compute=compute,
role=role,
environment={
"FLOPS_METER_NVML": "1",
},
)
model_trainer.train()
Because pretraining FLOPs are not known for this model, the PRETRAIN_FLOPS environment variable is omitted. The default threshold is applied automatically.
Compliance documentation
At training completion, the callback generates a flops_meter.json file containing the metrics n
関連記事
今日のまとめ
AI日報で今日の重要ニュースをまとめ読み