AI와 탄소: ML 교육의 규모 측정 및 줄이기
GPT-4 훈련은 대략 소모되었습니다. 50GWh의 전력, 충분하다 1년 동안 4,600개 이상의 유럽 주택에 전력을 공급할 수 있습니다. 그 전신인 GPT-3는 그는 생산했다 CO2 환산량 502톤 훈련 중 — 이는 휘발유 자동차 112대가 연간 20,000km를 주행하는 것과 같습니다. 프랑스에서 에너지 교육을 받은 1,760억 개의 매개변수 오픈 소스 모델인 BLOOM 혼합, 그는 발행 CO2eq 25톤 널리 사용된 덕분에 원자력과 재생에너지의.
이는 통계적인 호기심이 아닙니다. 빠르게 발전하는 구조적 문제의 징후입니다. 가속. 생성적 AI는 패턴을 통해 기하급수적으로 성장합니다. 점점 더 커져가는 데이터 세트와 더욱 커진 훈련 주기 자주. 에 발표된 연구에 따르면 자연 2024년에는 다음과 관련된 배출량이 발생합니다. 아무런 조치도 취하지 않으면 AI 모델 훈련이 2027년까지 3배 증가할 수 있습니다. 체계적인 효율성. IEA는 2026년 AI 전용 데이터 센터가 소비할 것으로 추정한다. 많은 중간 규모의 유럽 국가보다 더 많은 에너지를 보유하고 있습니다.
그러나 대다수의 ML 팀은 측정을 하지 않고 GPU 클러스터에서 훈련을 시작합니다. 생성된 배출물. 관심이 없어서가 아니라 도구가 부족하기 때문입니다. 일상적인 작업흐름에 통합되어 표준 지표와 측정 문화를 공유합니다. 이 시리즈의 마지막 기사에서 그린소프트웨어공학 우리는 탐구할 것이다 머신러닝을 통한 탄소발자국의 전체 라이프사이클: 정확한 측정부터 CodeCarbon 및 CarbonTracker, 가지치기 및 증류를 통한 아키텍처 최적화, 생산 시 탄소 인식 교육 일정 및 추론 최적화까지 가능합니다.
무엇을 배울 것인가
- 기본 모델의 실제 배출 데이터: GPT-3, GPT-4, Llama 2, BLOOM, PaLM
- CodeCarbon, CarbonTracker, ML CO2 Impact 및 친환경 알고리즘 설치 및 사용
- 전력 효율성을 위한 GPU 비교: FLOPS/와트 단위 A100, H100, H200, B200
- 아키텍처 최적화 기술: 가지치기, 지식 증류, 효율적인 NAS
- 데이터 중심 효율성: 데이터 품질과 양, 커리큘럼 학습
- 탄소 인식 교육: 탄소 강도가 낮은 지역 및 시간에 따라 작업 부하를 예약합니다.
- 추론 최적화: INT8/INT4 양자화, ONNX 런타임, TensorRT, vLLM
- ML 모델의 SCI 점수를 계산하고 친환경 AI 리더보드 구축
- 전체 사례 연구: 실제 NLP 모델에서 배출량 60% 감소
- 조직의 Green AI 도입을 위한 실무 로드맵
그린 소프트웨어 엔지니어링 시리즈 — 10개 기사
| # | Articolo | 메인테마 |
|---|---|---|
| 1 | 그린 소프트웨어 기반 원칙 | GSF, SCI, 8가지 기본 원칙 |
| 2 | CodeCarbon으로 탄소 배출량 측정 | CodeCarbon, CCF, CI/CD 통합 |
| 3 | Climatiq API 및 탄소 회계 | REST API, LCA, 범위 1-2-3 |
| 4 | 탄소 인식 SDK 및 시간/공간 이동 | 워크로드를 친환경 에너지로 전환 |
| 5 | 범위 모델링 및 SCI 구현 | 실용적인 SCI 계산, Impact Framework |
| 6 | GreenOps: 지속 가능성을 위한 FinOps | 클라우드 비용과 탄소, Kubernetes |
| 7 | 소프트웨어 파이프라인의 범위 3 | 간접 배출, 디지털 공급망 |
| 8 | ESG, CSRD 및 디지털 보고 | 유럽 규정 준수, ESRS E1, 공개 |
| 9 | 지속 가능한 아키텍처 패턴 | 스토리지, 캐싱, 탄소 인식 배치 |
| 10 | AI 및 Carbon: ML 훈련 공간 | 이 기사 — 시리즈의 마지막 기사 |
기초 모델의 실제 탄소 배출량
문제의 규모를 이해하려면 하드 데이터가 필요합니다. 스탠포드 연구원 Hugging Face와 MLCommons는 메이저 기업에 대한 배출량 측정항목을 게시하기 시작했습니다. 언어 모델. 다음 표는 사용 가능한 데이터를 집계한 것입니다. 많은 회사, 특히 OpenAI는 여전히 이 정보를 공개하지 않습니다.
훈련 중 기본 모델의 CO2eq 배출량
| 모델 | 매개변수 | 에너지(MWh) | CO²eq(t) | 지역/믹스 | 원천 |
|---|---|---|---|---|---|
| GPT-3 | 175B | 1,287 | 502 | 미국(중간 혼합) | Pattersonet al. 2021 |
| GPT-4 | ~1.8T(추정) | ~50,000 | ~14,000 | 미국 (추정) | 독립 추정치 2023 |
| BLOOM | 176B | 433 | 25 | 프랑스(원자력+재생) | Luccioniet al. 2022년 |
| 라마 2 (70B) | 70B | ~700 | 539 | 미국/애저 | 2023년 메타 FW |
| 손바닥 안에 감추다 | 540B | ~3,400 | ~507 | 미국(TPU v4) | Chowdheryet al. 2022년 |
| 미스트랄 7B | 7B | ~35 | ~12 | 유럽(혼합) | 미스트랄 FW 2023 |
| 팔콘 180B | 180B | ~600 | ~117 | UAE (혼합) | TII 2023 |
| 보석 7B | 7B | ~32 | ~6 | 미국/TPU(RE100) | 구글 딥마인드 2024 |
이 데이터는 세 가지 기본 패턴을 보여줍니다. 첫 번째는 지리적 격차: 프랑스에서 주로 원자력으로 훈련받은 BLOOM, 배출량이 20배 적음 라마 2의 크기도 동일합니다. 두 번째는규모 효과: 매개변수를 7B에서 176B로 바꾸는 것은 단순히 배출량이 25배 더 많다는 것을 의미하지 않습니다. 분산된 통신 비용과 교육 기간은 비선형적으로 증가합니다. 세 번째는 투명성 격차: 대부분의 회사는 그렇지 않습니다. 여전히 이 데이터를 게시하므로 비교가 어렵고 벤치마킹이 불가능합니다. 독립적인 측정 없이.
추론의 역설: 훈련 그 이상
직관과는 반대로, 누적 배출량은추론 그들은 종종 초과 모델의 수명주기에 대한 교육입니다. 수백만 개의 ChatGPT와 같은 모델 일일 요청 수는 생산 한 달 동안 더 많은 에너지를 소비할 수 있습니다. 전체 원래 훈련의. Pattersonet al. 규모에 대한 GPT-3의 추론을 추정 ChatGPT는 대략적인 결과를 생성합니다. 연간 CO2eq 11,000톤. 이 교육 최적화에서 추론 최적화로 초점을 이동합니다. 전체 환경 영향을 줄이는 것이 최우선 과제입니다.
내재된 배출 및 전체 수명주기
AI 탄소발자국 분석은 활동 중에 소비되는 에너지에만 국한될 수 없습니다. 훈련. 그만큼 구체화된 방출 하드웨어 — 배출되는 CO2 GPU, 서버, 냉각 네트워크 및 인프라를 생산합니다. 상당한 점유율. 단일 H100 칩을 생산하면 약 150kgCO²eq, 1,000개의 GPU 클러스터는 하드웨어만으로 약 150톤의 탄소 배출량을 배출합니다. 단일 학습 작업을 시작하기도 전에.
# Formula Carbon Footprint Completo per ML
# Basato su Luccioni et al. "Counting Carbon" (2023)
Total_CO2eq = Training_CO2eq + Inference_CO2eq + Embodied_CO2eq
Training_CO2eq = Energy_training (kWh) x Carbon_Intensity (kgCO2eq/kWh) x PUE
Inference_CO2eq = (Requests x Latency x GPU_Power / 3600000) x Carbon_Intensity x PUE
Embodied_CO2eq = (Hardware_Production_CO2eq / Lifespan_hours) x Training_hours
# Esempio: modello NLP medio (BERT-Large fine-tuning su task classificazione)
Energy_training = 120 kWh # 4x A100, 6 ore
Carbon_Intensity = 0.420 kg/kWh # mix europeo medio
PUE = 1.3 # data center tipico
Training_CO2eq = 120 x 0.420 x 1.3 = 65.5 kgCO2eq
# Inferenza: 10M richieste/mese, 50ms each, 1x A100 (300W)
Inference_monthly = (10_000_000 x 0.05 x 300 / 3_600_000) x 0.420 x 1.3
= 41.7 kWh x 0.420 x 1.3 = 22.7 kgCO2eq/mese
# Dopo 12 mesi: 272 kgCO2eq inferenza vs 65 kgCO2eq training
# L'inferenza domina del 77% nel ciclo di vita annuale
측정 도구: CodeCarbon에서 친환경 알고리즘까지
ML 배출량을 측정하려면 ML 워크로드용으로 특별히 설계된 도구가 필요합니다. 훈련과 추론. 4가지 도구가 공간을 지배합니다: CodeCarbon, CarbonTracker, ML CO₂ 영향 계산기 및 친환경 알고리즘. 모든 사람은 특정한 강점을 가지고 있습니다. 그리고 최적의 사용 사례.
CodeCarbon: Python 코드에 직접 통합
CodeCarbon은 배출가스 측정에 가장 널리 사용되는 도구입니다. ML 훈련. 가장 일반적인 프레임워크(PyTorch, TensorFlow, Hugging Face Transformers)는 대부분의 팀에서 자연스러운 선택입니다.
# pip install codecarbon
from codecarbon import EmissionsTracker, track_emissions
import torch
from transformers import Trainer, TrainingArguments
# Metodo 1: Context manager
tracker = EmissionsTracker(
project_name="bert-finetuning-sentiment",
country_iso_code="ITA",
region="lombardy",
cloud_provider="gcp",
cloud_region="europe-west8",
output_dir="./carbon_reports",
output_file="emissions.csv",
log_level="warning",
save_to_file=True,
tracking_mode="machine", # Legge sensori hardware reali
measure_power_secs=15 # Campionamento ogni 15 secondi
)
tracker.start()
try:
# Il tuo training loop qui
model = train_model(dataset, epochs=10)
finally:
emissions = tracker.stop()
print(f"Training completato: {emissions:.4f} kgCO2eq")
print(f"Equivalente a: {emissions * 2.4:.2f} km in auto")
# Metodo 2: Decorator per funzioni singole
@track_emissions(
project_name="bert-inference",
country_iso_code="ITA",
save_to_file=True
)
def run_inference_batch(model, dataloader):
results = []
with torch.no_grad():
for batch in dataloader:
outputs = model(**batch)
results.extend(outputs.logits.argmax(-1).tolist())
return results
# Metodo 3: Integrazione con Hugging Face Trainer
from codecarbon import EmissionsTracker
class CarbonAwareTrainer(Trainer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.carbon_tracker = EmissionsTracker(
project_name=f"hf-training-{self.args.run_name}",
country_iso_code="ITA",
save_to_file=True
)
def train(self, *args, **kwargs):
self.carbon_tracker.start()
result = super().train(*args, **kwargs)
emissions = self.carbon_tracker.stop()
self.log({"carbon_emissions_kgCO2eq": emissions})
return result
CarbonTracker: 예측 및 예산 책정
코펜하겐 대학교에서 개발한 CarbonTracker는 뛰어난 성능을 자랑합니다. 의 프로젝트 총 소비 첫 번째 훈련 기간을 기준으로 합니다. 이 기능은 매우 중요합니다. 이를 통해 탄소 비용을 추정할 수 있습니다. 며칠 또는 몇 주 동안 지속되는 훈련을 완료하기 전에.
# pip install carbontracker
from carbontracker.tracker import CarbonTracker
from carbontracker import parser
# Configurazione con proiezione
tracker = CarbonTracker(
epochs=100,
epochs_before_pred=5, # Dopo 5 epoche, proietta le 95 rimanenti
monitor_epochs=10, # Monitora ogni 10 epoche
log_dir="./carbontracker_logs",
update_interval=10,
verbose=2,
components="gpu",
ignore_errors=False
)
for epoch in range(100):
tracker.epoch_start()
# Training epoch
for batch in train_loader:
optimizer.zero_grad()
outputs = model(batch['input_ids'], batch['attention_mask'])
loss = criterion(outputs, batch['labels'])
loss.backward()
optimizer.step()
tracker.epoch_end()
tracker.stop()
# Dopo 5 epoche, CarbonTracker stampa proiezioni come:
# "Predicting training to use 2.34 kWh and emit 0.98 kgCO2eq"
# "Total: actual consumption: 0.12 kWh, 0.05 kgCO2eq (after 5 epochs)"
# Parsing dei log per analisi
logs = parser.parse_all_logs(log_dir="./carbontracker_logs")
for log in logs:
print(f"Energia: {log['actual']['energy (kWh)']:.3f} kWh")
print(f"CO2: {log['actual']['co2eq (g)']:.1f} gCO2eq")
print(f"Proiezione totale: {log['pred']['co2eq (g)']:.1f} gCO2eq")
ML CO₂ 영향 계산기 및 친환경 알고리즘
ML CO₂ 영향 계산기 (mlco2.github.io)는 웹 도구입니다. 하드웨어, 클라우드 공급자, 지역 및 기간을 기준으로 배출량을 추정합니다. 필요하지 않음 코드에 통합: 빠른 사전 훈련 추정 또는 문서화에 이상적 교육 문제가 이미 완료되었습니다. AWS, GCP, Azure 및 15개 이상의 지역을 지원합니다.
친환경 알고리즘 (green-algorithms.org), 대학에서 개발 Cambridge의 에너지 소비 모델에 대한 보다 과학적인 접근 방식을 제공합니다. 실제 데이터 센터 데이터에서 검증되었습니다. HPC(고성능 컴퓨팅) 계산을 지원합니다. GPU 클러스터 및 생물정보학 워크플로우.
ML 탄소 측정 도구 비교
| 기구 | 유형 | 세분성 | 완성 | 강점 | 한정 |
|---|---|---|---|---|---|
| 코드카본 | 파이썬 라이브러리 | 기능/직무 | PyTorch, T.F., H.F | 실제 하드웨어 측정 | Python만 해당, 오버헤드 <1% |
| 탄소 추적기 | 파이썬 라이브러리 | 시대를 위해 | 딥 러닝 루프 | 조기 중단 심사 | 시대 기반 교육이 필요합니다. |
| ML CO₂ 영향 | 웹 도구 | 직업레벨 | 없음(웹 양식) | 제로 설정, 빠른 견적 | 측정이 아닌 추정만 가능 |
| 친환경 알고리즘 | 웹 도구 | 직업레벨 | 없음(웹 양식) | 과학적으로 검증된 모델 | 실시간이 아님 |
| 실험 영향 추적기 | 파이썬 라이브러리 | 실험 | ML 실험 | 자동 MLflow 로깅 | 최소한의 유지 관리(2021) |
대시보드 및 자동 보고
측정은 데이터가 집계되고 시각화되어 측정에 사용되는 경우에만 가치가 있습니다. 결정. 효과적인 패턴은 CodeCarbon을 MLflow와 통합하여 성능 지표와 함께 배출량을 기록하는 자동 추적 시스템입니다.
import mlflow
from codecarbon import EmissionsTracker
import pandas as pd
from pathlib import Path
class GreenMLExperiment:
"""Wrapper che traccia automaticamente emissioni + performance ML."""
def __init__(self, experiment_name: str, country_code: str = "ITA"):
self.experiment_name = experiment_name
self.country_code = country_code
mlflow.set_experiment(experiment_name)
def run(self, model_fn, train_fn, eval_fn, params: dict):
with mlflow.start_run():
mlflow.log_params(params)
# Avvia tracker emissioni
tracker = EmissionsTracker(
project_name=self.experiment_name,
country_iso_code=self.country_code,
save_to_file=True,
output_dir="./emissions_logs"
)
tracker.start()
model = model_fn(**params)
train_metrics = train_fn(model)
emissions_kg = tracker.stop()
# Metriche performance
eval_metrics = eval_fn(model)
# Log tutto su MLflow
mlflow.log_metric("train_loss", train_metrics["loss"])
mlflow.log_metric("eval_accuracy", eval_metrics["accuracy"])
mlflow.log_metric("emissions_kgCO2eq", emissions_kg)
mlflow.log_metric("emissions_grams", emissions_kg * 1000)
mlflow.log_metric(
"accuracy_per_kgCO2",
eval_metrics["accuracy"] / max(emissions_kg, 0.001)
)
# Log artefatti
mlflow.log_artifacts("./emissions_logs")
return {
"model": model,
"emissions": emissions_kg,
"metrics": eval_metrics,
"efficiency_ratio": eval_metrics["accuracy"] / emissions_kg
}
# Utilizzo
experiment = GreenMLExperiment("bert-sentiment-v2", country_code="ITA")
result = experiment.run(
model_fn=create_bert_model,
train_fn=train_epoch,
eval_fn=evaluate_model,
params={"lr": 2e-5, "batch_size": 32, "epochs": 5}
)
GPU 에너지 효율성: 와트당 FLOPS
하드웨어 선택은 탄소 배출량에 가장 영향을 미치는 결정입니다. 훈련의. 차세대 GPU는 훨씬 더 높은 에너지 효율성을 제공합니다. 이전 모델과 비교했을 때 A100과 H200의 훈련 차이는 다음을 의미할 수 있습니다. 동일한 작업 부하에 대해 배출량이 40~60% 감소합니다.
ML 훈련을 위한 GPU 비교: 에너지 효율성(2025)
| GPU | 년도 | TDP(승) | FP16 TFLOPS | 플롭/와트 | HBM 메모리 | CO2 상대 |
|---|---|---|---|---|---|---|
| A100 SXM4 | 2020 | 400W | 312 | 780GFLOPS/W | 80GB HBM2e | 기준선(1.0x) |
| H100 SXM5 | 2022년 | 700W | 989 | 1.413GFLOPS/W | 80GB HBM3 | 0.56배(-44%) |
| H200 SXM5 | 2024년 | 700W | 989 | 1.413GFLOPS/W | 141GB HBM3e | 0.56배(-44%) |
| B200 SXM6 | 2025년 | 1,000W | 4,500 | 4,500GFLOPS/W | 192GB HBM3e | 0.17x (-83%) |
| RTX 4090 | 2022년 | 450W | 165 | 367GFLOPS/W | 24GB GDDR6X | 2.12배(+112%) |
| AMD MI300X | 2024년 | 750W | 1,307 | 1.743GFLOPS/W | 192GB HBM3 | 0.45x(-55%) |
H100 및 H200은 대략적으로 제공됩니다. 배출량 44% 감소 존경 FP8을 탑재한 Transformer Engine과 아키텍처 덕분에 동일한 작업 부하를 A100으로 NVLink가 최적화되었습니다. B200은 4.5 PFLOPS 및 FP16으로 세대적 도약을 나타냅니다. 기본 FP4 지원을 통해 83%로 감소합니다.
혼합 정밀 훈련: FP16 및 BF16
훈련은 혼합 정밀도 (계산용은 FP16 또는 BF16, 계산용은 FP32) 모델 매개변수) 훈련에 비해 에너지 소비를 30~50% 줄입니다. 모델 품질이 크게 저하되지 않고 전체 FP32.
import torch
from torch.cuda.amp import autocast, GradScaler
# Training con AMP (Automatic Mixed Precision)
scaler = GradScaler()
def train_epoch_amp(model, dataloader, optimizer, device):
model.train()
total_loss = 0.0
for batch in dataloader:
input_ids = batch['input_ids'].to(device)
labels = batch['labels'].to(device)
optimizer.zero_grad()
# Forward pass in FP16/BF16
with autocast(dtype=torch.bfloat16): # BF16 su A100/H100
outputs = model(input_ids=input_ids, labels=labels)
loss = outputs.loss
# Backward pass con gradient scaling
scaler.scale(loss).backward()
scaler.unscale_(optimizer)
# Gradient clipping per stabilità
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
scaler.step(optimizer)
scaler.update()
total_loss += loss.item()
return total_loss / len(dataloader)
# Con Hugging Face: basta un flag
from transformers import TrainingArguments
training_args = TrainingArguments(
output_dir="./results",
bf16=True, # BF16 per A100/H100 (preferibile a FP16)
fp16=False,
dataloader_num_workers=4,
per_device_train_batch_size=32,
gradient_accumulation_steps=4, # Simula batch da 128
gradient_checkpointing=True, # -40% memoria VRAM, +20% tempo
# Risparmio energetico: meno transfer GPU-CPU
dataloader_pin_memory=True
)
# Benchmark: BERT-Large su 1M esempi
# FP32: 6.2 ore, 148 kWh, 62 kgCO2eq (ITA)
# BF16: 3.4 ore, 81 kWh, 34 kgCO2eq (ITA) -> -45% emissioni
아키텍처 최적화: 가지치기, 증류 및 NAS
아키텍처 최적화 기술은 모델 복잡성을 줄이고, 더 빠른 훈련, 더 효율적인 추론 및 탄소 배출량으로 이어집니다. 전반적으로 감소했습니다. 세 가지 주요 기술은 가지치기, 지식 증류입니다. 효율적인 신경 아키텍처 검색.
모델 가지치기: 중복 제거
가지치기를 통해 미미하게 기여하는 모델 매개변수 또는 구조가 제거됩니다. 정확성을 위해. 두 가지 주요 접근 방식이 있습니다. 구조화되지 않은 가지치기 (개별 가중치) e 구조화된 가지치기 (주의 머리, 뉴런, 레이어). 실제 하드웨어 효율성을 위해서는 후자가 더 좋습니다. 가지치기에는 실제로 이점을 얻으려면 지원이 부족한 하드웨어가 필요합니다.
import torch
import torch.nn.utils.prune as prune
from transformers import BertForSequenceClassification
import numpy as np
def structured_pruning_bert(model, pruning_ratio=0.3):
"""
Pruning strutturato delle teste di attenzione BERT.
Rimuove le teste meno importanti basandosi sulla norma L1.
"""
pruned_heads = {}
for layer_idx, layer in enumerate(model.bert.encoder.layer):
# Calcola importanza di ogni testa (norma L1 dei pesi query)
attention = layer.attention.self
num_heads = attention.num_attention_heads
head_size = attention.attention_head_size
query_weights = attention.query.weight.data # shape: [hidden, hidden]
query_reshaped = query_weights.view(num_heads, head_size, -1)
head_importance = query_reshaped.abs().mean(dim=[1, 2])
# Seleziona le teste da prunable
num_heads_to_prune = int(num_heads * pruning_ratio)
heads_to_prune = head_importance.argsort()[:num_heads_to_prune].tolist()
if heads_to_prune:
pruned_heads[layer_idx] = set(heads_to_prune)
model.prune_heads(pruned_heads)
return model, pruned_heads
# Unstructured pruning con PyTorch
def magnitude_pruning(model, sparsity=0.5):
"""Pruning per magnitudine su tutti i layer Linear."""
parameters_to_prune = [
(module, 'weight')
for module in model.modules()
if isinstance(module, torch.nn.Linear)
]
prune.global_unstructured(
parameters_to_prune,
pruning_method=prune.L1Unstructured,
amount=sparsity
)
# Rende il pruning permanente
for module, param in parameters_to_prune:
prune.remove(module, param)
return model
# Risultati tipici su BERT-Base (110M parametri):
# Pruning 30% teste: -28% latenza inferenza, -1.2% accuracy
# Pruning 50% pesi (magnitude): -45% dimensione, -0.8% accuracy
# Emissioni inferenza: -30% con structured pruning
지식 증류: 큰 지식을 갖춘 작은 모델
지식 증류는 하나의 대형 모델(교사)에서 다른 모델로 지식을 전달합니다. 작다 (학생). 예를 들어 DistilBERT는 BERT-Base 매개변수의 40%를 가지고 있지만 GLUE 벤치마크에서 97%의 성능을 유지합니다. 훈련 방출 DistilBERT는 60% 낮고 추론은 40~50%입니다.
import torch
import torch.nn as nn
import torch.nn.functional as F
class DistillationLoss(nn.Module):
"""
Loss combinata per knowledge distillation:
L = alpha * L_CE(student, labels) + (1-alpha) * L_KL(student, teacher)
"""
def __init__(self, alpha=0.5, temperature=4.0):
super().__init__()
self.alpha = alpha
self.temperature = temperature
self.ce_loss = nn.CrossEntropyLoss()
def forward(self, student_logits, teacher_logits, labels):
# Loss classificazione standard
loss_ce = self.ce_loss(student_logits, labels)
# Loss distillazione (KL divergence con temperature scaling)
student_soft = F.log_softmax(student_logits / self.temperature, dim=-1)
teacher_soft = F.softmax(teacher_logits / self.temperature, dim=-1)
loss_kl = F.kl_div(student_soft, teacher_soft, reduction='batchmean')
loss_kl *= self.temperature ** 2 # Scala per compensare la temperature
return self.alpha * loss_ce + (1 - self.alpha) * loss_kl
def distill_model(teacher_model, student_model, train_loader,
optimizer, device, epochs=5):
"""Training loop completo per knowledge distillation."""
distill_loss = DistillationLoss(alpha=0.5, temperature=4.0)
teacher_model.eval()
for epoch in range(epochs):
student_model.train()
total_loss = 0.0
for batch in train_loader:
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
labels = batch['labels'].to(device)
# Teacher inference (no gradient)
with torch.no_grad():
teacher_outputs = teacher_model(
input_ids=input_ids,
attention_mask=attention_mask
)
# Student forward pass
student_outputs = student_model(
input_ids=input_ids,
attention_mask=attention_mask
)
loss = distill_loss(
student_outputs.logits,
teacher_outputs.logits,
labels
)
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_loss += loss.item()
print(f"Epoch {epoch+1}: Loss = {total_loss/len(train_loader):.4f}")
# Caso d'uso tipico: distillare BERT-Large (340M) -> BERT-Tiny (14M)
# Training: 8h vs 2.5h -> -69% tempo
# Emissioni training: -71%
# Accuracy GLUE: 84.6 vs 87.2 -> -3% accettabile per la maggior parte dei task
효율적인 신경 아키텍처 검색
기존 NAS는 아이러니하게도 가장 에너지 집약적인 프로세스 중 하나입니다. ML에서: 최적의 아키텍처를 검색하려면 수천 번의 완전한 교육 세션이 필요할 수 있습니다. 그만큼 효율적인 NAS 원샷 NAS, 체중 공유와 같은 기술을 사용합니다. 예측자 기반 검색을 통해 검색 비용을 99% 절감합니다.
# Esempio con Once-for-All Network (OFA) da MIT
# OFA addestra una volta una supernetwork, poi campiona subnetwork efficienti
# Installazione: pip install ofa
from ofa.model_zoo import ofa_net
# Carica supernetwork pre-addestrata (una volta sola)
ofa_network = ofa_net('ofa_resnet50', pretrained=True)
# Campiona subnetwork che rispettano constraint energetici
# senza riaddestrare (zero-cost NAS)
def find_efficient_subnet(ofa_net, target_flops: float = 200e6):
"""
Cerca una subnetwork con FLOPs < target_flops
usando evolutionary search con predictor di accuracy.
"""
from ofa.nas.search_algorithm import EvolutionFinder
finder = EvolutionFinder(
constraint_type='flops',
efficiency_constraint=target_flops,
efficiency_predictor=ofa_net.flops_counter,
accuracy_predictor=None, # Usa validazione reale
population_size=100,
max_time_budget=500,
parent_ratio=0.25,
mutation_ratio=0.5
)
best_valset_acc, best_info = finder.run_evolution_search()
return best_info['net_config']
# Risultato tipico:
# Supernetwork ResNet-50: 4.1 GFLOPs, 25.6M param
# Subnetwork trovata: 200 MFLOPs, 6.2M param
# Accuracy ImageNet: 77.8% vs 79.2% (- 1.4%, - 95% emissioni inferenza)
데이터 중심 효율성: 품질과 수량
더 높은 품질의 데이터세트를 사용하면 동일한 정확도를 얻을 수 있습니다. 더 적은 훈련 시대와 더 적은 데이터를 사용합니다. 이는 의 원칙 중 하나입니다. 데이터 중심 AI Andrew Ng가 추진함: 모델을 늘리는 대신 또는 원시 데이터, 기존 데이터의 품질을 향상시킵니다.
커리큘럼 학습: 올바른 순서로 교육
학습 커리큘럼은 난이도를 높여서 훈련 사례를 주문합니다. 단순한 개념으로 시작하여 복잡한 개념으로 넘어가는 교사와 같습니다. 이 접근 방식은 더 빠르고 더 적은 수의 총 에포크로 수렴하므로 표준 벤치마크에서 탄소 배출량은 20-35%입니다.
import numpy as np
from torch.utils.data import DataLoader, SubsetRandomSampler
from sklearn.metrics import pairwise_distances
class CurriculumScheduler:
"""
Curriculum Learning: ordina il dataset dalla difficolta' crescente.
La difficolta' e' calcolata come distanza dalla media della classe.
"""
def __init__(self, dataset, difficulty_metric='loss', num_stages=4):
self.dataset = dataset
self.num_stages = num_stages
self.difficulty_scores = None
def compute_difficulty(self, model, device):
"""Calcola difficolta' come loss su un modello pre-addestrato leggero."""
model.eval()
scores = []
loader = DataLoader(self.dataset, batch_size=256, shuffle=False)
criterion = nn.CrossEntropyLoss(reduction='none')
with torch.no_grad():
for batch in loader:
input_ids = batch['input_ids'].to(device)
labels = batch['labels'].to(device)
outputs = model(input_ids=input_ids)
losses = criterion(outputs.logits, labels)
scores.extend(losses.cpu().numpy())
self.difficulty_scores = np.array(scores)
return self.difficulty_scores
def get_stage_indices(self, stage: int) -> list:
"""Ritorna gli indici degli esempi per lo stage corrente."""
if self.difficulty_scores is None:
raise ValueError("Esegui compute_difficulty prima.")
# Divide il dataset in quartili di difficolta'
sorted_indices = np.argsort(self.difficulty_scores)
stage_size = len(sorted_indices) // self.num_stages
# Stage 0: esempi più' facili, Stage N: tutti gli esempi
max_idx = stage_size * (stage + 1)
return sorted_indices[:max_idx].tolist()
def curriculum_training(model, dataset, optimizer, device, total_epochs=20):
"""Training con curriculum progressivo."""
scheduler = CurriculumScheduler(dataset, num_stages=4)
# Usa un modello leggero per calcolare la difficolta'
tiny_model = load_tiny_model().to(device)
difficulty = scheduler.compute_difficulty(tiny_model, device)
for epoch in range(total_epochs):
# Progressione lineare: da 25% a 100% del dataset
stage = min(3, int(epoch / total_epochs * 4))
indices = scheduler.get_stage_indices(stage)
sampler = SubsetRandomSampler(indices)
loader = DataLoader(dataset, batch_size=32, sampler=sampler)
print(f"Epoch {epoch}: usando {len(indices)}/{len(dataset)} esempi")
train_one_epoch(model, loader, optimizer, device)
# Risultati tipici:
# Training standard BERT-Base: 10 epoche per convergenza
# Training con curriculum: 6.5 epoche -> -35% emissioni
능동적 학습: 가장 유익한 데이터 선택
능동적 학습은 가장 유익한 사례를 반복적으로 선택하여 라벨을 지정하고, 전체 데이터 세트를 사용하는 대신. 10~20%의 주석 예산으로 달성됩니다. 종종 전체 데이터 훈련 정확도의 90-95%, 비례적으로 감소 탄소 발자국.
from sklearn.cluster import KMeans
import torch.nn.functional as F
class ActiveLearningSelector:
"""Seleziona esempi con massima incertezza (uncertainty sampling)."""
def __init__(self, model, unlabeled_pool, strategy='entropy'):
self.model = model
self.unlabeled_pool = unlabeled_pool
self.strategy = strategy
def compute_uncertainty(self, batch_size=128) -> np.ndarray:
"""Calcola incertezza del modello su ogni esempio non etichettato."""
self.model.eval()
uncertainties = []
loader = DataLoader(self.unlabeled_pool, batch_size=batch_size)
with torch.no_grad():
for batch in loader:
logits = self.model(batch['input_ids']).logits
probs = F.softmax(logits, dim=-1)
if self.strategy == 'entropy':
# Entropia: massima quando la distribuzione e' uniforme
entropy = -(probs * probs.log()).sum(dim=-1)
uncertainties.extend(entropy.cpu().numpy())
elif self.strategy == 'margin':
# Margin: minimo quando le top-2 prob sono simili
top2 = probs.topk(2, dim=-1).values
margin = top2[:, 0] - top2[:, 1]
uncertainties.extend((1 - margin).cpu().numpy())
return np.array(uncertainties)
def select_examples(self, n_select: int) -> list:
"""Seleziona i n_select esempi più' incerti."""
uncertainties = self.compute_uncertainty()
top_indices = np.argsort(uncertainties)[-n_select:]
return top_indices.tolist()
# Workflow Active Learning
def active_learning_loop(
model, labeled_data, unlabeled_pool,
annotation_budget=500, iterations=5
):
per_iteration = annotation_budget // iterations
for iteration in range(iterations):
# Seleziona esempi
selector = ActiveLearningSelector(model, unlabeled_pool)
selected_idx = selector.select_examples(per_iteration)
# Simula annotazione (in produzione: etichettatura umana)
new_labeled = [unlabeled_pool[i] for i in selected_idx]
labeled_data.extend(new_labeled)
# Riaddestra su dati aggiornati
model = fine_tune(model, labeled_data)
acc = evaluate(model)
print(f"Iter {iteration}: {len(labeled_data)} esempi, acc={acc:.3f}")
return model
# Con 500 esempi attivi vs 5000 casuali: stesso livello di accuracy
# Risparmio training: -90% dati -> -85% emissioni
탄소 인식 교육: 지능적으로 교육 일정을 계획하세요
탄소 인식 교육은 Carbon Aware SDK의 원리를 적용한 것입니다. ML 세계로: 엔지니어가 구성을 마쳤을 때 교육을 시작하는 대신 실험을 통해 우리는 시간과 가장 낮은 지역에 작업을 예약합니다. 전기 혼합의 탄소 강도.
시간 이동: 친환경 훈련이 있을 때
에너지의 탄소 강도는 하루 종일 엄청나게 다양합니다. 재생 가능 에너지의 가용성에 따라 매주. 이탈리아에서는 가장 푸르른 시간(여름에는 11:00~15:00)과 가장 푸르른 시간의 차이 석탄(겨울철 오후 7시~10시)은 200~300gCO²eq/kWh입니다.
import asyncio
import httpx
from datetime import datetime, timedelta
from typing import Optional
import subprocess
ELECTRICITY_MAPS_TOKEN = "YOUR_TOKEN" # electricitymaps.com/api
async def get_carbon_intensity(zone: str = "IT") -> float:
"""Recupera l'intensità' carbonica attuale dalla Electricity Maps API."""
async with httpx.AsyncClient() as client:
resp = await client.get(
f"https://api.electricitymap.org/v3/carbon-intensity/latest",
params={"zone": zone},
headers={"auth-token": ELECTRICITY_MAPS_TOKEN}
)
data = resp.json()
return data["carbonIntensity"] # gCO2eq/kWh
async def get_forecast(zone: str = "IT", hours: int = 24) -> list[dict]:
"""Recupera le previsioni di intensità' carbonica per le prossime ore."""
async with httpx.AsyncClient() as client:
resp = await client.get(
f"https://api.electricitymap.org/v3/carbon-intensity/forecast",
params={"zone": zone},
headers={"auth-token": ELECTRICITY_MAPS_TOKEN}
)
data = resp.json()
return data["forecast"][:hours]
async def find_optimal_training_window(
job_duration_hours: float,
zone: str = "IT",
max_delay_hours: int = 24
) -> Optional[datetime]:
"""
Trova la finestra temporale ottimale per un training job.
Cerca il window di 'job_duration_hours' con intensità' media minima.
"""
forecast = await get_forecast(zone, hours=max_delay_hours + int(job_duration_hours))
if not forecast:
return None
window_size = max(1, int(job_duration_hours))
best_start = None
best_avg_intensity = float('inf')
for i in range(len(forecast) - window_size + 1):
window = forecast[i:i + window_size]
avg_intensity = sum(h['carbonIntensity'] for h in window) / len(window)
if avg_intensity < best_avg_intensity:
best_avg_intensity = avg_intensity
best_start = datetime.fromisoformat(forecast[i]['datetime'])
print(f"Finestra ottimale: {best_start}")
print(f"Intensità' media: {best_avg_intensity:.1f} gCO2eq/kWh")
return best_start
async def carbon_aware_submit(
training_command: str,
job_duration_hours: float = 6.0,
threshold_gco2_kwh: float = 200.0,
zone: str = "IT"
):
"""
Submette un training job solo quando l'intensità' e' sotto soglia,
altrimenti aspetta la finestra ottimale.
"""
current = await get_carbon_intensity(zone)
if current <= threshold_gco2_kwh:
print(f"Intensità' attuale {current} gCO2/kWh: avvio immediato")
subprocess.Popen(training_command.split())
return
print(f"Intensità' troppo alta ({current} gCO2/kWh > {threshold_gco2_kwh})")
optimal_window = await find_optimal_training_window(
job_duration_hours, zone
)
if optimal_window:
wait_seconds = (optimal_window - datetime.now()).total_seconds()
print(f"Scheduling per {optimal_window} (attesa: {wait_seconds/3600:.1f}h)")
await asyncio.sleep(max(0, wait_seconds))
subprocess.Popen(training_command.split())
# Utilizzo
asyncio.run(carbon_aware_submit(
training_command="python train_bert.py --epochs 10",
job_duration_hours=8.0,
threshold_gco2_kwh=150.0,
zone="IT"
))
공간적 변화: 가장 친환경적인 클라우드 지역 선택
클라우드 제공업체마다 에너지 혼합이 매우 다른 지역을 제공합니다. 훈련 지역을 선택하면 배출량을 70~90%까지 줄일 수 있습니다. 무작위 선택과 비교.
클라우드 지역별 탄소 집약도 평균(2024-2025)
| 공급자 | 지역 | 위치 | gCO²eq/kWh | 메모 |
|---|---|---|---|---|
| GCP | 유럽-북부1 | 핀란드 | ~35 | 수력 + 풍력 |
| AWS | eu-북쪽-1 | 스톡홀름 | ~40 | 거의 100% 재생 가능 |
| GCP | 유럽-서부1 | 벨기에 | ~56 | 재생 가능 + 핵 혼합 |
| 하늘빛 | 프랑스 중부 | 파리 | ~58 | 핵우세 |
| AWS | eu-웨스트-1 | 아일랜드 | ~250 | 천연가스 보급 |
| AWS | 미국-동부-1 | 여자 이름 | ~296 | 중동 미국 믹스 |
| AWS | ap-남동쪽-1 | 싱가포르 | ~408 | 천연가스 |
# Spot Instances per training carbon-aware
# Le spot instance non solo riducono i costi del 60-90%,
# ma tendono a essere distribuite su hardware più' recente ed efficiente
import boto3
from botocore.exceptions import ClientError
def submit_spot_training(
image_uri: str,
instance_type: str = "p4d.24xlarge", # 8x A100
region: str = "eu-north-1", # Stoccolma: ~40 gCO2/kWh
max_price_per_hour: float = 15.0
):
"""Submette un training job su spot instances AWS SageMaker."""
sagemaker = boto3.client('sagemaker', region_name=region)
response = sagemaker.create_training_job(
TrainingJobName=f"green-ml-{int(datetime.now().timestamp())}",
AlgorithmSpecification={
'TrainingImage': image_uri,
'TrainingInputMode': 'FastFile'
},
ResourceConfig={
'InstanceType': instance_type,
'InstanceCount': 1,
'VolumeSizeInGB': 100
},
# Managed Spot Training
EnableManagedSpotTraining=True,
StoppingCondition={
'MaxRuntimeInSeconds': 86400, # 24 ore max
'MaxWaitTimeInSeconds': 172800 # Aspetta fino a 48 ore
},
# Checkpointing per riprendere se lo spot viene interrotto
CheckpointConfig={
'S3Uri': f's3://my-bucket/checkpoints/',
'LocalPath': '/opt/ml/checkpoints'
}
)
return response['TrainingJobArn']
# Confronto costi e emissioni:
# p4d.24xlarge on-demand (us-east-1): $32.77/h, 296 gCO2/kWh
# p4d.24xlarge spot (eu-north-1): $9.83/h, 40 gCO2/kWh
# Risparmio economico: -70%
# Risparmio emissioni: -86% (spot + regione verde)
추론 최적화: 탄소 배출량의 77%
예상한 대로, 생산에 대한 추론은 에너지 수명주기의 배출량을 지배합니다. ML 모델. 수백만 명의 사용자가 있는 모델의 경우 지연 시간이 밀리초 단위로 단축됩니다. 소비량이 감소할 때마다 연간 수십억 건의 요청이 증가합니다. 주요 기술은 양자화, 모델 컴파일, 최적화된 일괄 처리입니다.
양자화: INT8, INT4 및 GPTQ
양자화는 FP32 또는 FP16에서 모델 가중치의 수치 정밀도를 감소시킵니다. 8 또는 4비트 정수로. 이를 통해 메모리 요구 사항이 50~75% 감소하고 추론 속도가 향상됩니다. 2~4배 정도 줄어들고 이에 비례하여 에너지 소비도 낮아집니다.
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
import torch
# Quantizzazione INT4 con GPTQ (post-training quantization)
quantization_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_use_double_quant=True, # QLoRA: double quantization
bnb_4bit_quant_type="nf4" # Normal Float 4: migliore qualità'
)
model_id = "meta-llama/Llama-2-7b-hf"
model = AutoModelForCausalLM.from_pretrained(
model_id,
quantization_config=quantization_config,
device_map="auto",
torch_dtype=torch.bfloat16
)
tokenizer = AutoTokenizer.from_pretrained(model_id)
# Verifica riduzione memoria
original_size_gb = 7 * 2 / 1024 # 7B param x 2 byte (FP16) / 1024
quantized_size_gb = 7 * 0.5 / 1024 # 7B param x 0.5 byte (INT4) / 1024
print(f"FP16: {original_size_gb:.1f} GB")
print(f"INT4: {quantized_size_gb:.1f} GB (-{(1-quantized_size_gb/original_size_gb)*100:.0f}%)")
# Quantizzazione INT8 con ONNX Runtime (per produzione)
from optimum.onnxruntime import ORTModelForSequenceClassification
from optimum.onnxruntime.configuration import AutoQuantizationConfig
# Esporta in ONNX e quantizza
ort_model = ORTModelForSequenceClassification.from_pretrained(
"bert-base-uncased",
export=True
)
quantization_config = AutoQuantizationConfig.avx512_vnni(
is_static=False, # Dynamic quantization (no calibration data needed)
per_channel=False
)
# Salva il modello quantizzato
from optimum.onnxruntime import ORTQuantizer
quantizer = ORTQuantizer.from_pretrained(ort_model)
quantizer.quantize(
save_dir="./bert-int8-onnx",
quantization_config=quantization_config
)
# Benchmark:
# BERT-Base FP32: 23ms latenza, 100% accuracy, 1.6 GB
# BERT-Base INT8: 12ms latenza, 99.2% accuracy, 0.4 GB -> -48% energia
# BERT-Base INT4: 8ms latenza, 97.8% accuracy, 0.2 GB -> -65% energia
vLLM: LLM을 위한 효율적인 서비스
vLLM 이는 LLM을 위한 서비스 프레임워크입니다. Paged주의 KV 캐시를 훨씬 더 효율적으로 관리할 수 있습니다. 순진한 서빙에 비하면, vLLM은 동일한 하드웨어로 처리량을 15~24배 증가시켜 비례적으로 감소합니다. 생성된 토큰당 에너지 소비량.
from vllm import LLM, SamplingParams
from codecarbon import EmissionsTracker
# Avvia LLM con vLLM (PagedAttention + continuous batching)
llm = LLM(
model="meta-llama/Llama-2-7b-chat-hf",
tensor_parallel_size=1, # GPU count
gpu_memory_utilization=0.90, # Usa il 90% della VRAM per KV cache
max_num_batched_tokens=32768, # Batch maggiori = più' efficiente
quantization="awq" # AWQ quantization integrata
)
sampling_params = SamplingParams(
temperature=0.7,
max_tokens=256
)
# Misura emissioni per 1000 richieste
tracker = EmissionsTracker(project_name="vllm-inference-benchmark")
tracker.start()
prompts = ["Spiega il concetto di machine learning in italiano"] * 1000
outputs = llm.generate(prompts, sampling_params)
emissions = tracker.stop()
tokens_generated = sum(len(o.outputs[0].token_ids) for o in outputs)
print(f"Token generati: {tokens_generated:,}")
print(f"Emissioni: {emissions*1000:.2f} gCO2eq")
print(f"gCO2eq per 1000 token: {emissions*1000/tokens_generated*1000:.4f}")
# Confronto con serving naive HuggingFace:
# HuggingFace Transformers: 1.000 req, 45 min, 890 gCO2eq
# vLLM: 1.000 req, 3 min, 59 gCO2eq (-93%)
# Throughput: 333 req/min vs 22 req/min
ML 모델의 SCI 점수: 측정 표준화
사양 SCI(탄소 강도 소프트웨어) 그린 소프트웨어 재단의 이제 표준 ISO/IEC 21031:2024가 ML 시스템에도 적용됩니다. SCI는 배출량을 표현합니다. 기능 단위별로 서로 다른 모델 간의 의미 있는 비교가 가능합니다.
ML 시스템에 적용되는 SCI 공식
| 요소 | ML 공식 | BERT 추론 예시 |
|---|---|---|
| E (에너지) | GPU 전력 x 시간 / 1000 | 300W x 0.05s / 1000 = 0.000015kWh |
| I (탄소강도) | 지역의 gCO²eq/kWh | 420 gCO²eq/kWh(이탈리아 평균) |
| M (구현) | 하드웨어 CO₂ / (수명 x 사용량) | 150,000gCO₂ / (26,280h x 0.7) = 8.2g/h |
| R (기능 단위) | 1,000개의 추론 또는 1개의 토큰 생성 | 1,000개 분류 |
| 스키 | (E x I + M) / R | (0.015 x 0.420 + 0.00023) / 1 = 0.0065 gCO²eq/req |
from dataclasses import dataclass
from typing import Literal
@dataclass
class MLSystemSCI:
"""Calcola SCI Score per sistemi ML."""
model_name: str
gpu_count: int
gpu_tdp_watts: float
avg_latency_ms: float # Per inferenza singola
carbon_intensity_g_kwh: float # gCO2/kWh regione
gpu_lifespan_hours: float = 26_280 # 3 anni
gpu_embodied_gco2: float = 150_000 # ~150 kgCO2 per GPU
utilization: float = 0.70
pue: float = 1.3
functional_unit: Literal['request', 'token'] = 'request'
def operational_energy_kwh(self) -> float:
"""Energia operativa per singola inferenza."""
return (
self.gpu_count
* self.gpu_tdp_watts
* (self.avg_latency_ms / 1000)
/ 1_000 # W -> kW
)
def operational_emissions_g(self) -> float:
"""Emissioni operative per singola inferenza (gCO2eq)."""
return (
self.operational_energy_kwh()
* self.carbon_intensity_g_kwh
* self.pue
)
def embodied_per_request_g(self) -> float:
"""Quota embodied per singola inferenza."""
# Secondi per richiesta / secondi per vita GPU
fraction_of_life = (self.avg_latency_ms / 1000) / (
self.gpu_lifespan_hours * 3600
)
total_embodied = self.gpu_count * self.gpu_embodied_gco2
return total_embodied * fraction_of_life / self.utilization
@property
def sci_score(self) -> float:
"""SCI = (E x I + M) / R per singola richiesta."""
return self.operational_emissions_g() + self.embodied_per_request_g()
# Confronto modelli
models = [
MLSystemSCI("BERT-Base INT8/CPU", 0, 100, 45, 420, gpu_count=0,
gpu_embodied_gco2=0),
MLSystemSCI("BERT-Base FP32/A100", 1, 400, 12, 420),
MLSystemSCI("BERT-Base INT8/A100", 1, 280, 6, 420),
MLSystemSCI("DistilBERT FP16/A100", 1, 240, 5, 420),
MLSystemSCI("BERT-Base INT8/eu-north-1", 1, 280, 6, 40), # Stoccolma
]
print(f"{'Modello':<35} {'SCI (gCO2/req)':<18} {'vs Baseline'}")
baseline = models[0].sci_score
for m in models:
sci = m.sci_score
ratio = sci / baseline
print(f"{m.model_name:<35} {sci:.6f} gCO2 {ratio:.2f}x")
그린 AI 리더보드: 정확성보다 효율성
GLUE, SuperGLUE, MMLU와 같은 기존 리더보드는 정확성만 측정합니다. 개념 그린 AI 리더보드, Schwartz 등이 제안함. (2020) 2024년 GSF에 의해 공식화되었으며 균형을 이루는 복합 측정항목을 도입합니다. 성능과 탄소 효율성.
친환경 AI 지표: 정확도/배출량 절충(GLUE 벤치마크)
| 모델 | GLUE 점수 | CO²eq 열차(t) | CO2eq 추정(mg/req) | 그린 스코어* |
|---|---|---|---|---|
| BERT 기반 | 82.1 | 0.9 | 0.62 | 132 |
| RoBERTa-베이스 | 86.4 | 4.1 | 0.62 | 139 |
| 디스틸버트 | 77.0 | 0.35 | 0.31 | 248 |
| BERT 기반 INT8 | 81.3 | 0.9 | 0.28 | 290 |
| 모바일BERT | 78.2 | 0.6 | 0.18 | 434 |
| ALBERT-Base v2 | 82.3 | 0.5 | 0.42 | 196 |
* 그린 점수 = (GLUE 점수 / CO2eq 추론) x 1000. 값이 높을수록 더 효율적입니다.
DistilBERT가 BERT-Base보다 GLUE 점수가 6% 낮음에도 불구하고 어떻게 그린 스코어가 거의 두 배에 달합니다. MobileBERT는 목록에서 최고의 Green Score를 제공합니다. 탄소 예산이 제한된 대규모 배포를 위한 최적의 선택입니다.
사례 연구: NLP 모델에서 탄소 배출량 60% 감소
이 사례 연구에서는 모델에 적용되는 실제 최적화 경로를 설명합니다. 회사를 위해 개발된 이탈리아 시장의 감정 분류 처리해야 할 월별 리뷰가 200만 건에 달하는 전자상거래의
기준선: 초기 상태
# STATO INIZIALE (Baseline)
# Modello: bert-base-multilingual-cased (177M parametri)
# Hardware: 1x NVIDIA A100 80GB SXM4 (on-demand AWS us-east-1)
# Task: classificazione sentiment 5 classi (1-5 stelle)
# Dataset: 500.000 recensioni in italiano
# Metriche baseline:
Training_time_hours = 18.5
Energy_training_kWh = 130.0 # A100 SXM4: ~400W TDP, PUE=1.5
CO2_training_kgCO2eq = 38.5 # 130 kWh x 0.296 kgCO2/kWh (us-east-1)
Inference_latency_ms = 35.0 # Per singola recensione
Inference_throughput_req_s = 28.6
CO2_inference_per_1M_req = 2.85 # kgCO2eq
Monthly_inference_requests = 2_000_000
Monthly_inference_CO2_kg = 5.70
Annual_training_runs = 4 # Re-training trimestrale
Annual_total_CO2_kg = (4 * 38.5) + (12 * 5.70) = 222.4
Accuracy_f1_macro = 0.847
단계별 최적화
# STEP 1: Cambio regione cloud (us-east-1 -> eu-north-1)
# Carbon intensity: 296 -> 40 gCO2/kWh (-86%)
# Nessun cambiamento al codice, solo flag AWS Region
CO2_training_kgCO2eq_step1 = 130.0 * 0.040 * 1.5 = 7.8 # -80%
Monthly_inference_CO2_step1 = 2.85 * (40/296) = 0.38 # -87%
Annual_CO2_step1 = (4 * 7.8) + (12 * 0.38) = 35.7 kg # -84%
# STEP 2: Cambio modello base (multilingual -> umberto italiano)
# umberto-commoncrawl-cased (bert-base size ma solo italiano)
# Dataset training ridotto del 30% (solo dati italiani puliti)
# Curriculum learning: 15 epoche vs 20 -> -25% training time
CO2_training_kgCO2eq_step2 = 7.8 * 0.75 * 0.70 = 4.1 # -47% su step1
Accuracy_f1_macro_step2 = 0.861 # +1.4% grazie a modello specializzato
# STEP 3: Quantizzazione INT8 (ONNX Runtime)
# Latenza inferenza: 35ms -> 18ms (-49%)
# Throughput: 28.6 -> 55.5 req/s (+94%)
Inference_latency_ms_step3 = 18.0
Monthly_inference_CO2_step3 = 0.38 * 0.50 = 0.19 # -50%
Accuracy_f1_macro_step3 = 0.856 # -0.5% accettabile
# STEP 4: Carbon-aware scheduling del re-training
# Spot instances + finestre energetiche verdi
# Costo spot eu-north-1: -70% vs on-demand
# Timing training nelle ore di massima rinnovabile
CO2_training_kgCO2eq_step4 = 4.1 * 0.85 = 3.5 # Spot: stesso hardware, timing migliore
# RIEPILOGO OTTIMIZZAZIONI
print("=" * 60)
print(f"Baseline: {222.4:.1f} kgCO2eq/anno | F1: 0.847")
print(f"Step 1: {35.7:.1f} kgCO2eq/anno | -84% (solo regione)")
print(f"Step 2: {26.9:.1f} kgCO2eq/anno | -87% (modello+data)")
print(f"Step 3: {21.7:.1f} kgCO2eq/anno | -90% (quantizzazione)")
print(f"Step 4: {18.6:.1f} kgCO2eq/anno | -92% (carbon-aware)")
print(f"F1 finale: 0.856 vs 0.847 baseline (+1.1%)")
print("=" * 60)
print(f"Riduzione CO2: -203.8 kgCO2eq/anno (-91.6%)")
print(f"Risparmio costi: -74% (spot + regione + efficienza)")
사례 연구 결과: 요약
| 미터법 | 기준선 | 최적화됨 | 변화 |
|---|---|---|---|
| 총 연간 CO²eq | 222kgCO²eq | 19kgCO²eq | -91% |
| F1-점수 매크로 | 0.847 | 0.856 | +1.1% |
| 추론 대기 시간 | 35ms | 18ms | -49% |
| 처리량 | 28 요청/초 | 55 요청/초 | +96% |
| 월간 클라우드 비용 | ~2,400유로 | ~620유로 | -74% |
핵심 교훈: 정확도를 유지하면서 배출량의 90%가 감소합니다.
이 사례 연구에서 각 최적화 단계에는 개선됨 또는 모델의 정확성을 유지했습니다. 저장된 클라우드 지역 선택 코드 한 줄도 건드리지 않고 배출량의 84%를 달성했습니다. 전문화 이탈리아어용 템플릿의 품질이 향상되었습니다. 양자화 대기 시간이 절반으로 줄었습니다. 메시지는 분명합니다: 탄소 최적화 발자국과 품질 최적화는 상충되는 목표가 아닙니다.
조직을 위한 그린 AI 로드맵
Green AI를 채택한다고 해서 모든 것을 즉시 혁신할 필요는 없습니다. 로드맵 3단계로 시작하여 점진적으로 관행을 도입할 수 있습니다. 더 큰 효과와 더 적은 노력으로 최적화합니다.
3단계 그린 AI 도입 로드맵
| 단계 | 타임라인 | 행위 | CO2 감소 기대 |
|---|---|---|---|
| 1단계: 측정 | 1~4주차 |
모든 훈련 작업에 CodeCarbon을 설치하십시오. 모델당 배출 기준선을 정의합니다. 더 친환경적인 클라우드 지역을 선택하세요 |
50-85%(지역만 해당) |
| 2단계: 최적화 | 2~4개월 |
모든 훈련에 혼합 정밀도(BF16)를 적용합니다. 생산 중인 모델을 양자화합니다(INT8). 배치 훈련을 위해 스팟 인스턴스 채택 |
추가 30-50% |
| 3단계: 통합 | 5~12개월 |
탄소 인식 자동 스케줄링; 내부 그린 AI 리더보드; 배치 기준의 SCI 점수; ESG 보고 ML 배출량 |
추가 10-20% |
각 훈련 작업에 대한 친환경 AI 체크리스트
# Checklist Green AI da seguire prima di ogni training
# Copia in: .github/PULL_REQUEST_TEMPLATE.md o come commento training script
CHECKLIST_GREEN_AI = """
Green AI Pre-Training Checklist
================================
[ ] 1. REGIONE: Training schedulato in regione con CI < 150 gCO2/kWh?
Verifica: https://app.electricitymaps.com/zone/IT
Preferisci: GCP europe-north1, AWS eu-north-1, Azure swedencentral
[ ] 2. TIMING: Carbon-aware scheduling attivato?
Tool: Carbon Aware SDK o script custom
Finestra ottimale: verificata nelle ultime 24h
[ ] 3. HARDWARE: GPU di ultima generazione disponibile?
H100 >> A100 (44% più' efficiente)
Spot/preemptible instances preferite
[ ] 4. PRECISION: Mixed precision attivata (BF16/FP16)?
HuggingFace: bf16=True in TrainingArguments
PyTorch: torch.autocast('cuda', dtype=torch.bfloat16)
[ ] 5. EARLY STOPPING: Configurato con CarbonTracker per proiezione?
Stima emissioni dopo 5 epoche e confronta con budget CO2
[ ] 6. TRACKING: CodeCarbon configurato?
Country_iso_code, cloud_provider, cloud_region impostati
Output in: ./carbon_reports/
[ ] 7. DATI: Dataset ottimizzato con deduplication e qualità'?
Almeno 10% redundancy rimossa
Active learning per ridurre dimensione se possibile
[ ] 8. BASELINE: Esiste una run precedente da confrontare?
Registra su MLflow: accuracy, emissioni, ratio
[ ] 9. INFERENZA: Quantizzazione pianificata per produzione?
Target: INT8 con ONNX Runtime o INT4 per LLM
[ ] 10. REPORTING: Emissioni saranno incluse nel model card?
Usa: SCI Score, kgCO2eq training, gCO2eq/1000 req inferenza
"""
print(CHECKLIST_GREEN_AI)
결론: 친환경 소프트웨어 엔지니어링 시리즈 요약
이 기사로 시리즈를 마무리합니다 그린소프트웨어공학, 실천의 전체 스펙트럼을 넘나드는 10개의 기사로 구성된 여정 지속 가능한 소프트웨어 개발. GSF 원칙 이론부터 구현까지 CodeCarbon, Carbon Aware SDK, Climatiq API를 사용한 사례와 기술까지 고급 ML 최적화: 우리는 다음을 위한 포괄적인 툴킷을 구축했습니다. 디지털 환경에 미치는 영향을 줄이려는 개발자 및 조직.
시리즈의 10가지 핵심 메시지
| # | Articolo | 핵심 메시지 |
|---|---|---|
| 1 | GSF 원칙 | 탄소 효율성은 소프트웨어 품질 지표입니다. |
| 2 | 코드카본 | 측정하지 않는 것을 줄일 수는 없습니다. 첫날부터 시작하세요. |
| 3 | Climatiq API | CO₂에는 API가 있습니다. 탄소 회계를 백엔드에 통합하세요 |
| 4 | 탄소 인식 SDK | 시간이나 공간에 따른 워크로드 이동을 90% 줄일 수 있습니다. |
| 5 | 범위 모델링 | SCI는 소프트웨어의 탄소 효율성을 비교하는 ISO 표준입니다. |
| 6 | GreenOps | Green과 FinOps의 조화: CO2 최적화로 클라우드 비용 절감 |
| 7 | 범위 3 파이프라인 | 간접 배출은 직접 배출보다 더 큰 경우가 많습니다. |
| 8 | ESG 및 CSRD | 2025년부터 디지털 ESG 보고는 많은 기업의 법적 의무가 됩니다. |
| 9 | 지속 가능한 패턴 | 캐시, 배치 및 비동기는 단순한 성능이 아니라 친환경 패턴입니다. |
| 10 | AI 카본 | 클라우드 지역을 선택하면 어떤 알고리즘보다 ML 방출이 줄어듭니다. |
그 순간은 바로 지금이다
생성 AI는 계속해서 성장할 것입니다. 모델이 더 커질 것입니다. 교육을 자주 실시할수록 배포가 더욱 광범위해집니다. 질문은 그렇지 않습니다. AI 배출량이 증가한다면 어쨌든 증가할 것입니다. 그러나 그 양은 얼마나 될까요? 이 기사의 기술은 60-90% 감소가 가능함을 보여줍니다. 정확도를 저하시키지 않고 ML 시스템의 방출을 줄입니다. 비용. 이것은 타협이 아닙니다. 모든 면에서 승리한 것입니다.
Green Software Foundation은 모든 ML 팀이 다음과 같은 관행을 채택한다면 탄소 인식 교육 및 추론의 양자화, 해당 부문의 글로벌 배출량 AI는 다음과 같이 줄어들 수 있습니다. 2030년까지 40-60% 시나리오에 비해 평소대로. 우리는 기술적 혁신이 필요하지 않습니다. 설명된 관행이 필요합니다. 이 10개의 기사를 체계적으로 적용해보세요.
다음 단계는 당신의 것입니다. 다음 교육 작업에 CodeCarbon을 설치하세요. AWS 또는 GCP 지역의 탄소 강도를 확인하세요. 양자화 모델을 배포하기 전에 SCI 점수를 측정합니다. 그리고 그렇게 할 때, 당신은 가장 중요한 단계, 즉 시작을 하게 될 것입니다.
유용한 링크 및 도구
- 코드카본: mlco2.github.io/codecarbon
- ML CO₂ 영향 계산기: mlco2.github.io/impact
- 친환경 알고리즘 계산기: green-algorithms.org
- 전기 지도 API: electricmaps.com/api
- GSF SCI 사양: sci.greensoftware.foundation
- 포옹 얼굴 배출 추적기: HuggingFace 허브 탄소 추적
- vLLM 제공: docs.vllm.ai
- ONNX 런타임 최적화: onnxruntime.ai
계속되는 길: 관련 시리즈
- 비즈니스용 MLOps: ML 모델 배포에 대해 자세히 알아보세요. 탄소 배출량 품질 게이트를 포함한 MLflow, DVC 및 CI/CD 파이프라인.
- AI 엔지니어링 및 RAG: RAG 시스템 구축 방법 살펴보기 LLM 모델에 대한 호출 수를 최소화하여 두 가지를 모두 줄이는 것이 효율적입니다. 배출하는 비용.
- 데이터 & AI 사업: AI Act EU 및 규정에 대해 알아보세요. ESG는 Green AI 관행과 교차하며 로드맵을 구축하는 방법 중소기업을 위한 지속 가능한 데이터 기반.







