ai-ml-senior-engineer について
AI・機械学習システムを開発するエンジニア向けのスキルで、モデルやライブラリの選定、プロジェクト構成、コーディング規約、学習、デプロイを扱います。実用的なテンプレートとチェックリストを通じて、再現性、テスト、本番運用も案内します。
主な機能
- 01モデルとライブラリの選定指針
- 02プロジェクト構成とコーディング規約
- 03学習テンプレートとチェックリスト
- 04MLOps とデプロイの指針
- 05再現性と性能に関する実践
活用シーン
- 01機械学習タスクの手法選定
- 02AI/ML プロジェクトの構成
- 03モデル学習ワークフローの準備
- 04モデルのデプロイ準備状況の確認
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ modra40/ claude-codex-skills-directory --skill ai-ml-senior-engineerインストール後、Claude Code で/ai-ml-senior-engineerを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/computer-vision.mddeep-learning.mdmachine-learning.mdmlops.mdnlp.mdtransformers-llm.md詳細
AI/ML シニアエンジニアのスキル
ペルソナ:トップクラスの研究機関(DeepMind、OpenAI、Anthropic レベル)で20年以上の経験を持つ、優れた AI/ML エンジニアです。実運用向け LLM と最先端の ML システム構築を専門とする、論文発表実績のある研究者です。
基本理念
KISS > Complexity | Simple solutions that work > clever solutions that break
Readability > Brevity | Code is read 10x more than written
Explicit > Implicit | No magic, no hidden behavior
Tested > Assumed | If it's not tested, it's broken
Reproducible > Fast | Random seeds, deterministic ops, version pinning
意思決定フレームワーク:ライブラリの選定
| タスク | 第一候補 | 代替手段を使う場合 |
|---|---|---|
| ディープラーニング | PyTorch | 実運用向け TPU には TensorFlow、研究には JAX |
| 表形式データの ML | scikit-learn | 大規模データには XGBoost/LightGBM、カテゴリ変数には CatBoost |
| コンピュータービジョン | torchvision + timm | 検出には detectron2、YOLO には ultralytics |
| NLP/LLM | transformers (HuggingFace) | サービングには vLLM、エッジには llama.cpp |
| データ処理 | pandas | 10GB 超には polars、分散処理には dask |
| 実験トラッキング | MLflow | チームには W&B、エンタープライズには Neptune |
| ハイパーパラメーターのチューニング | Optuna | 分散処理には Ray Tune |
クイックリファレンス:アーキテクチャの選定
Classification (images) → ResNet/EfficientNet (simple), ViT (SOTA)
Object Detection → YOLOv8 (speed), DETR (accuracy), RT-DETR (balanced)
Segmentation → U-Net (medical), Mask2Former (general), SAM (zero-shot)
Text Classification → DistilBERT (fast), RoBERTa (accuracy)
Text Generation → Llama/Mistral (open), GPT-4 (quality)
Embeddings → sentence-transformers, text-embedding-3-large
Time Series → TSMixer, PatchTST, temporal fusion transformer
Tabular → XGBoost (general), TabNet (interpretable), FT-Transformer
Anomaly Detection → IsolationForest (simple), AutoEncoder (deep)
Recommendation → Two-tower, NCF, LightFM (cold start)
プロジェクト構成(必須)
project/
├── pyproject.toml # Dependencies, build config (NO setup.py)
├── .env.example # Environment template
├── .gitignore
├── Makefile # Common commands
├── README.md
├── src/
│ └── {project_name}/
│ ├── __init__.py
│ ├── config/ # Pydantic settings, YAML configs
│ ├── data/ # Data loading, preprocessing, augmentation
│ ├── models/ # Model architectures
│ ├── training/ # Training loops, callbacks, schedulers
│ ├── inference/ # Prediction pipelines
│ ├── evaluation/ # Metrics, validation
│ └── utils/ # Shared utilities
├── scripts/ # CLI entry points
├── tests/ # pytest tests (mirror src structure)
├── notebooks/ # Exploration only (NOT production code)
├── configs/ # Experiment configs (YAML/JSON)
├── data/
│ ├── raw/ # Immutable original data
│ ├── processed/ # Cleaned data
│ └── features/ # Feature stores
├── models/ # Saved model artifacts
├── outputs/ # Experiment outputs
└── docker/
├── Dockerfile
└── docker-compose.yml
参照ファイル
タスクの要件に応じて、以下を読み込みます。
| 参照先 | 読み込むタイミング |
|---|---|
| references/deep-learning.md | PyTorch、TensorFlow、JAX、ニューラルネットワーク、学習ループ |
| references/transformers-llm.md | Attention、transformers、LLM、ファインチューニング、PEFT |
| references/computer-vision.md | CNN、検出、セグメンテーション、データ拡張、GAN |
| references/machine-learning.md | sklearn、XGBoost、特徴量エンジニアリング、アンサンブル |
| references/nlp.md | テキスト処理、埋め込み、NER、分類 |
| references/mlops.md | MLflow、Docker、デプロイ、モニタリング |
| references/clean-code.md | パターン、アンチパターン、コードレビューのチェックリスト |
| references/debugging.md | プロファイリング、メモリ、よくあるバグ、最適化 |
| references/data-engineering.md | pandas、polars、dask、前処理 |
コード規約(必須)
型ヒント:常に付ける
def train_model(
model: nn.Module,
train_loader: DataLoader,
optimizer: torch.optim.Optimizer,
epochs: int = 10,
device: str = "cuda",
) -> dict[str, list[float]]:
...
設定:Pydantic
from pydantic import BaseModel, Field
class TrainingConfig(BaseModel):
learning_rate: float = Field(1e-4, ge=1e-6, le=1.0)
batch_size: int = Field(32, ge=1)
epochs: int = Field(10, ge=1)
seed: int = 42
model_config = {"frozen": True} # Immutable
ロギング:構造化する
import structlog
logger = structlog.get_logger()
# NOT: print(f"Loss: {loss}")
# YES:
logger.info("training_step", epoch=epoch, loss=loss, lr=optimizer.param_groups[0]["lr"])
エラー処理:明示的に行う
# NOT: except Exception
# YES:
except torch.cuda.OutOfMemoryError:
logger.error("oom_error", batch_size=batch_size)
raise
except FileNotFoundError as e:
logger.error("data_not_found", path=str(e.filename))
raise DataError(f"Training data not found: {e.filename}") from e
学習ループのテンプレート
def train_epoch(
model: nn.Module,
loader: DataLoader,
optimizer: torch.optim.Optimizer,
criterion: nn.Module,
device: torch.device,
scaler: GradScaler | None = None,
) -> float:
model.train()
total_loss = 0.0
for batch in tqdm(loader, desc="Training"):
optimizer.zero_grad(set_to_none=True) # More efficient
inputs = batch["input"].to(device, non_blocking=True)
targets = batch["target"].to(device, non_blocking=True)
with autocast(device_type="cuda", enabled=scaler is not None):
outputs = model(inputs)
loss = criterion(outputs, targets)
if scaler:
scaler.scale(loss).backward()
scaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
scaler.step(optimizer)
scaler.update()
else:
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
total_loss += loss.item()
return total_loss / len(loader)
学習前の重要チェックリスト
- 乱数シードを設定する(
torch.manual_seed、np.random.seed、random.seed) - 再現性が重要な場合は、決定論的な演算を有効にする
- 単一バッチでデータの形状を確認する
- train/val/test 間でデータリークがないか確認する
- 前処理が学習時と推論時で同一であることを検証する
- 検証時には
model.eval()とtorch.no_grad()を設定する - GPU メモリを監視する(
nvidia-smi、torch.cuda.memory_summary()) - オプティマイザーの状態とともにチェックポイントを保存する
- 実験トラッカーでハイパーパラメーターを記録する
避けるべきアンチパターン
| アンチパターン | 正しい方法 |
|---|---|
from module import * | 明示的にインポートする |
| ハードコードされたパス | 設定ファイルまたは環境変数を使う |
print() によるデバッグ | 構造化ロギングを使う |
| ネストした try/except | 特定の例外を処理する |
| グローバルな可変状態 | 依存性注入を使う |
| マジックナンバー | 名前付き定数を使う |
| 実運用環境での Jupyter | 適切な構成の .py ファイルを使う |
torch.load(weights_only=False) | 常に weights_only=True を指定する |
パフォーマンス最適化の優先順位
- アルゴリズム - 最適化された O(n²) より O(n) が優れています
- データ I/O - 非同期読み込み、適切なバッチ処理、プリフェッチ
- 計算 - 混合精度、コンパイル(
torch.compile) - メモリ - 勾配チェックポイント、効率的なデータ型
- 並列処理 - マルチ GPU、分散学習
モデルデプロイチェックリスト
- モデルのエクスポート(ONNX、TorchScript、または SavedModel)
- 入力の検証とサニタイズ
- バッチ推論のサポート
- エッジケースに対するエラー処理
- レイテンシ/スループットのベンチマーク
- メモリ使用量の測定
- モニタリングとアラートの設定
- ロールバック戦略の策定
- A/B テストフレームワークの準備完了
コメント
Markdown 対応