CodeCarbon
CodeCarbon is an open-source Python library that helps estimate and track the CO2 emissions produced by computing, particularly for machine learning models. It measures energy consumption of CPU, GPU, and RAM, and combines it with regional carbon intensity data to provide CO2 equivalent emissions. Currently at version 3.2.6, it maintains an active development and release cadence, offering both Python API and CLI for monitoring and reporting.
Common errors
-
Another instance of codecarbon is probably running as we find /tmp/.codecarbon.lock. Turn off the other instance to be able to run this one or use allow_multiple_runs or delete the file. Exiting.
cause An `EmissionsTracker` instance detected a lock file, indicating another tracker is active or a previous run terminated abnormally.fixIf you intended to run multiple trackers, initialize with `EmissionsTracker(allow_multiple_runs=True)`. Otherwise, ensure no other `codecarbon` process is running or manually delete the lock file (e.g., `/tmp/.codecarbon.lock` on Linux). -
ApiClient Error when calling the API on https://api.codecarbon.io/... API return http code 500 and answer : {"detail":"Generic error"}cause Failed communication with the CodeCarbon online API, often due to misconfigured API keys, project IDs, or network issues.fixVerify your internet connection. Check the `api_endpoint`, `api_key`, `organization_id`, `project_id`, and `experiment_id` in your global `~/.codecarbon.config` or local `.codecarbon.config` file. Re-run `codecarbon login` or `codecarbon config` CLI commands to re-authenticate and configure. -
AttributeError: module 'codecarbon' has no attribute 'EmissionsTracker'
cause The `EmissionsTracker` class was not found when attempting to import, likely due to a partial installation, a corrupted environment, or incorrect import statement.fixEnsure `codecarbon` is correctly installed: `pip install --upgrade codecarbon`. Verify the import statement: `from codecarbon import EmissionsTracker`. If running in an IDE, restart the Python kernel or environment. -
FileNotFoundError: [Errno 2] No such file or directory: 'emissions.csv'
cause Attempting to read `emissions.csv` before `EmissionsTracker.stop()` has been called, or the file was saved to a different location.fixEnsure `tracker.stop()` is called before trying to access `emissions.csv`. The file is saved in the directory where the script is run by default, or to a path specified by the `save_to_file` parameter in `EmissionsTracker`.
Warnings
- breaking Version 3.2.4 was broken due to packaging issues and was subsequently yanked from PyPI. Direct upgrades to 3.2.4 might have failed or resulted in a broken installation.
- breaking CodeCarbon has updated its underlying APIs for carbon intensity data (e.g., from CO2 Signal to Electricity Maps) and its authentication backend (from Fief to Keycloak). Users relying on specific API integrations or the CodeCarbon dashboard might need to update configurations or API keys.
- gotcha The accuracy of hardware power consumption measurements (CPU, GPU) depends on the availability of specific underlying tools (e.g., Intel Power Gadget/RAPL, pynvml, amdsmi) on your operating system. Without these, CodeCarbon will fall back to less accurate estimation methods.
- gotcha By default, CodeCarbon's `EmissionsTracker` uses a lock file to prevent multiple instances from running concurrently in the same directory, which can cause an error if a previous run crashed or if you intentionally try to run multiple trackers.
- gotcha CodeCarbon measures emissions from local computing (your hardware). It does not track emissions from remote GenAI API calls (e.g., OpenAI, Anthropic, Mistral). For those, CodeCarbon recommends using EcoLogits.
Install
-
pip install codecarbon -
conda install -c conda-forge codecarbon
Imports
- EmissionsTracker
from codecarbon import EmissionsTracker
- track_emissions
import codecarbon; codecarbon.track_emissions
from codecarbon import track_emissions
- OfflineEmissionsTracker
from codecarbon import OfflineEmissionsTracker
Quickstart
import time
from codecarbon import EmissionsTracker
def train_model():
# Simulate some computationally intensive task
print("Starting model training...")
time.sleep(10) # Your actual ML code here
print("Model training finished.")
if __name__ == "__main__":
tracker = EmissionsTracker()
tracker.start()
train_model()
emissions = tracker.stop()
print(f"Emissions: {emissions} kg CO₂")
print("Check emissions.csv for detailed report.")