# Cerebras Job Scheduling and Monitoring Source: https://training-docs.cerebras.ai/rel-2.5.0/cluster-monitoring/cerebras-job-scheduling-and-monitoring Learn more about how jobs are scheduled and monitored on Cerebras systems. Jobs submitted to the Cerebras Wafer-Scale cluster follow a first-come, first-served queuing system for resource allocation. This means that jobs are processed in the order they are received, and resources are assigned accordingly. To keep track of and manage your jobs in the Cerebras Wafer-Scale cluster, you can use various monitoring and management tools provided by Cerebras. While the specific tools may evolve over time, some common tools and techniques for monitoring the cluster include: * [CLI for job monitoring(csctl)](./cerebras-job-scheduling-and-monitoring/cli-for-job-monitoring-csctl): The csctl tool is designed to provide comprehensive job monitoring capabilities. With csctl, you can: * Inspect submitted jobs, gathering information about their status and configuration. * Assign labels to jobs for better organization and categorization. * Retrieve details about mounted volumes, which are crucial for data access. * Export logs to investigate job execution and troubleshoot issues efficiently. * [Job priority](./cerebras-job-scheduling-and-monitoring/job-priority): The job priority feature allows users to prioritize jobs in the Cerebras Wafer-Scale cluster based on priority buckets and values, enhancing job scheduling beyond the FIFO approach. Users can assign and adjust job priorities during submission or post-submission, with administrative controls over priority modifications, facilitating more efficient and organized job scheduling and execution. * [Cluster monitoring with Grafana](./cerebras-job-scheduling-and-monitoring/cluster-monitoring-with-grafana): Cerebras offers a Grafana dashboard that offers a visual representation of job resource usage and relevant software and hardware errors tied to specific jobs. Grafana provides an intuitive interface for tracking and analyzing cluster performance and job metrics. * slurm-integration: Cerebras has implemented a lightweight integration with the Slurm workload manager. Slurm is a job scheduler and resource manager widely used in high-performance computing environments. This integration streamlines job submission and management within the Cerebras Wafer-Scale cluster, allowing for efficient resource allocation and job scheduling. * resource\_parallel\_compile: You can define resource requirements for parallel training and compilation jobs running inside the Cerebras Wafer-Scale cluster. This includes setting limits on memory and CPU usage to ensure efficient resource allocation and prevent resource contention. These tools and integrations collectively empower users to effectively monitor, manage, and optimize their workloads on the Cerebras Wafer-Scale cluster. They provide visibility into job status, resource utilization, and potential issues, facilitating streamlined job execution and cluster operation. Additionally, they enhance user experience by simplifying job management tasks and promoting efficient resource allocation. # Job Monitoring CLI Source: https://training-docs.cerebras.ai/rel-2.5.0/cluster-monitoring/cerebras-job-scheduling-and-monitoring/cli-for-job-monitoring-csctl Learn how to use the csctl CLI tool to manage and monitor jobs. The `csctl` command-line interface (CLI) tool allows you to manage jobs on the cluster directly from the terminal of your user node. To learn more about the available commands, run: `csctl --help` ```Bash theme={null} csctl --help Cerebras cluster command line tool. Usage: csctl [command] Available Commands: cancel Cancel job check-volumes Check volume validity on this usernode clear-worker-cache Clear the worker cache config View csctl config files get Get resources job Job management commands label Label resources log-export Gather and download logs. types Display resource types Flags: --csconfig string config file /opt/cerebras/config_v2 (default "/opt/cerebras/config_v2") -d, --debug int higher debug values will display more fields in output objects -h, --help help for csctl -n, --namespace string configure csctl to talk to different user namespaces --version version for csctl Use "csctl [command] --help" for more information about a command. ``` ## Job IDs Each training job submitted to the cluster launches two sequential jobs, each with their own `jobID`: * a compilation job (this runs first) * an execution job (this runs once the compliation job is done) Job IDs are a required argument for most `csctl` commands. You can view the job ID in your terminal as each job is run: ```Bash theme={null} Extracting the model from framework. This might take a few minutes. WARNING:root:The following model params are unused: precision_opt_level, loss_scaling 2023-02-05 02:00:00,450 INFO: Compiling the model. This may take a few minutes. 2023-02-05 02:00:00,635 INFO: Initiating a new compile wsjob against the cluster server. 2023-02-05 02:00:00,761 INFO: Compile job initiated ... 2023-02-05 02:02:00,899 INFO: Ingress is ready. 2023-02-05 02:02:00,899 INFO: Cluster mgmt job handle: {'job_id': 'wsjob-aaaaaaaaaa000000000', 'service_url': 'cluster-server.cerebras.local:443', 'service_authority': 'wsjob-aaaaaaaaaa000000000-coordinator-0.cluster-server.cerebras.local', 'compile_dir_absolute_path': '/cerebras/cached_compile/cs_0000000000111111'} 2023-02-05 02:02:00,901 INFO: Creating a framework GRPC client: cluster-server.cerebras.local:443 2023-02-05 02:07:00,112 INFO: Compile successfully written to cache directory: cs_000000000011111 2023-02-05 02:07:30,118 INFO: Compile for training completed successfully! 2023-02-05 02:07:30,120 INFO: Initiating a new execute wsjob against the cluster server. 2023-02-05 02:07:30,248 INFO: Execute job initiated ... 2023-02-05 02:08:00,321 INFO: Ingress is ready. 2023-02-05 02:08:00,321 INFO: Cluster mgmt job handle: {'job_id': 'wsjob-bbbbbbbbbbb11111111', 'service_url': 'cluster-server.cerebras.local:443', 'service_authority': 'wsjob-bbbbbbbbbbb11111111-coordinator-0.cluster-server.cerebras.local', 'compile_artifact_dir': '/cerebras/cached_compile/cs_0000000000111111'} ... ``` Job IDs are also recorded in the `/cerebras_logs/run_meta.json` file, which contains two sections: `compile_jobs` and `execute_jobs`. For example, the compile job will show under `compile_jobs` while the training job and some additional log information will show under `execute_jobs`: ```Bash theme={null} { "compile_jobs": [ { "id": "wsjob-aaaaaaaaaa000000000", "log_path": "/cerebras/workdir/wsjob-aaaaaaaaaa000000000", "start_time": "2023-02-05T02:00:00Z", }, ] } ``` After the training job is scheduled, additional log information and the jobID of the training job will show under `execute_jobs`. To correlate between compilation job and training job, you can correlate between the available time of the compilation job and the start time of the training job. For this example, you will see ```Bash theme={null} { "compile_jobs": [ { "id": "wsjob-aaaaaaaaaa000000000", "log_path": "/cerebras/workdir/wsjob-aaaaaaaaaa000000000", "start_time": "2023-02-05T02:00:00Z", "cache_compile": { "location": "/cerebras/cached_compile/cs_0000000000111111", "available_time": "2023-02-05T02:02:00Z" } } ], "execute_jobs": [ { "id": "wsjob-bbbbbbbbbbb11111111", "log_path": "/cerebras/workdir/wsjob-bbbbbbbbbbb11111111", "start_time": "2023-02-05T02:02:00Z" } ] } ``` Using the `jobID`, query information about status of a job in the system: ```Bash theme={null} csctl [-d int] get job [-o json|yaml] ``` where: | Flag | Default | Description | | - | - | - | | -o | table | Output Format: table, json, yaml | | -d, -debug | 0 | Debug level. Choosing a higher level of debug prints more fields in the output objects. Only applicable to json or yaml output format. | ```Bash theme={null} csctl -d0 get job wsjob-000000000000 -oyaml meta: createTime: "2022-12-07T05:10:16Z" labels: label: customed_label user: user1 name: wsjob-000000000000 type: job spec: user: gid: "1001" uid: "1000" volumeMounts: - mountPath: /data name: data-volume-000000 subPath: "" - mountPath: /dev/shm name: dev-shm subPath: "" status: phase: SUCCEEDED systems: - systemCS2_1 ``` > [!NOTE] > > Compilation jobs do not require CS-X resources, but they do require resources on the server nodes. We allow only one concurrent compilation running in the cluster. Execution jobs require CS-X resources and will be queued up until those resources are available. Compilation and execution jobs have different job IDs. ## Cancel Jobs You can cancel any compilation or execution job with the `jobID`: ```Bash theme={null} csctl cancel job ``` Cancelling a job releases all resources and sets the job to a cancelled state. In 1.8, this command might cause the client logs to print ```Bash theme={null} cerebras.appliance.errors.ApplianceUnknownError: Received unexpected gRPC error (StatusCode.UNKNOWN) : 'Stream removed' while monitoring Coordinator for Runtime server errors ``` This is expected. ## Label Jobs Label a job with the `label` command: ```Bash theme={null} csctl label job wsjob-000000000000 framework=pytorch ``` Run the same command again to remove a label. ## Track Queue Obtain a full list of running and queued jobs on the cluster: ```Bash theme={null} csctl get jobs ``` By default, this command produces a table including: | Field | Description | | - | - | | Name | jobID identification | | Age | Time since job submission | | Duration | How long the job ran | | Phase | One of QUEUED, RUNNING, SUCCEDED, FAILED, CANCELLED | | Systems | CS-X systems used in this job | | User | User that starts this job | | Labels | Customized labels by user | | Dashboard | Grafana dashboard link for this job | For example: ```Bash theme={null} csctl get jobs NAME AGE DURATION PHASE SYSTEMS USER LABELS DASHBOARD wsjob-000000000001 18h 20s RUNNING systemCS2_1, systemCS2_2 user2 model=gpt3-tiny https://grafana.cerebras.local/d/WebHNShVz/wsjob-dashboard?orgId=1&var-wsjob=wsjob-000000000001 wsjob-000000000002 1h 6m25s QUEUED user2 model=neox,team=ml https://grafana.cerebras.local/d/WebHNShVz/wsjob-dashboard?orgId=1&var-wsjob=wsjob-000000000002 wsjob-000000000003 10m 2m01s QUEUED user1 model=gpt3-tiny https://grafana.cerebras.local/d/WebHNShVz/wsjob-dashboard?orgId=1&var-wsjob=wsjob-000000000003 ``` Directly executing the command prints out a long list of current and past jobs. Use `-l` to return jobs that match with the given set of labels: ```Bash theme={null} csctl get jobs -l model=neox,team=ml NAME AGE DURATION PHASE SYSTEMS USER LABELS DASHBOARD wsjob-000000000002 1h 6m25s QUEUED user2 model=neox,team=ml https://grafana.cerebras.local/d/WebHNShVz/wsjob-dashboard?orgId=1&var-wsjob=wsjob-000000000002 ``` If you only want to see your own jobs, use `-m`: ```Bash theme={null} csctl get jobs -m NAME AGE DURATION PHASE SYSTEMS USER LABELS DASHBOARD wsjob-000000000003 10m 2m01s QUEUED user1 model=gpt3-tiny https://grafana.cerebras.local/d/WebHNShVz/wsjob-dashboard?orgId=1&var-wsjob=wsjob-000000000003 ``` To also include completed and failed jobs, use `-a`: ```Bash theme={null} csctl get jobs -a NAME AGE DURATION PHASE SYSTEMS USER LABELS DASHBOARD wsjob-000000000000 43h 6m27s SUCCEEDED systemCS2_1 user1 model=gpt3xl https://grafana.cerebras.local/d/WebHNShVz/wsjob-dashboard?orgId=1&var-wsjob=wsjob-000000000000 wsjob-000000000001 18h 20s RUNNING systemCS2_1, systemCS2_2 user2 model=gpt3-tiny https://grafana.cerebras.local/d/WebHNShVz/wsjob-dashboard?orgId=1&var-wsjob=wsjob-000000000001 wsjob-000000000002 1h 6m25s QUEUED user2 model=neox,team=ml https://grafana.cerebras.local/d/WebHNShVz/wsjob-dashboard?orgId=1&var-wsjob=wsjob-000000000002 wsjob-000000000003 10m 2m01s QUEUED user1 model=gpt3-tiny https://grafana.cerebras.local/d/WebHNShVz/wsjob-dashboard?orgId=1&var-wsjob=wsjob-000000000003 ``` These filter options can be combined. For example, to see your complete job history: ```Bash theme={null} csctl get jobs -a -m NAME AGE DURATION PHASE SYSTEMS USER LABELS DASHBOARD wsjob-000000000000 43h 6m27s SUCCEEDED systemCS2_1 user1 model=gpt3xl https://grafana.cerebras.local/d/WebHNShVz/wsjob-dashboard?orgId=1&var-wsjob=wsjob-000000000000 wsjob-000000000003 10m 2m01s QUEUED user1 model=gpt3-tiny https://grafana.cerebras.local/d/WebHNShVz/wsjob-dashboard?orgId=1&var-wsjob=wsjob-000000000003 ``` You also can use `grep` to view which jobs are queued versus running and how many systems are occupied. `grep 'RUNNING'` will show a list of jobs that are currently running on the cluster. For example: ```Bash theme={null} csctl get jobs | grep 'RUNNING' wsjob-000000000001 18h 20s RUNNING systemCS2_1, systemCS2_2 user2 model=gpt3-tiny https://grafana.cerebras.local/d/WebHNShVz/wsjob-dashboard?orgId=1&var-wsjob=wsjob-000000000001 ``` `grep 'QUEUED'` will show a list of jobs that are currently queued. For example: ```Bash theme={null} csctl get jobs | grep 'QUEUED' wsjob-000000000002 1h 6m25s QUEUED user2 model=neox,team=ml https://grafana.cerebras.local/d/WebHNShVz/wsjob-dashboard?orgId=1&var-wsjob=wsjob-000000000002 ``` ## Get Configured Volumes Get a list of mounted volumes on the cluster: ```Bash theme={null} csctl get volume NAME TYPE CONTAINERPATH SERVER SERVERPATH READONLY training-data-volume nfs /ml 10.10.10.10 /ml false ``` ## Update Job Priority Update the priority for a given job, where `priority_value` is p1, p2, or p3: ```Bash theme={null} csctl job set-priority -n ``` For example: ```Bash theme={null} $ csctl job set-priority wsjob-xxxxxx -n mynamespace p2 ``` This updates the job’s priority to P2. ## Redundancy Pools If you're running a larger job with Auto Job Restart enabled, you can create a redundacy pool to ensure job continuity and system reliability. The system will utilize the redundacy pool only when: * Local session systems or nodes become unhealthy * Local session lacks sufficient resources to complete the job In those cases, resources from the redundant pool are used to complete the job. ### Limitations and Compatibility Requirements * Jobs must fit within the session's total system capacity. For example, a session with 2 total systems cannot submit a 3-system job, even if redundancy systems are available. * You cannot submit jobs directly to the redundant pool. If you need a redundant system for debugging purposes, system administrators can manually move redundancy systems to a debug session. * The redundancy pool session operates in a restricted mode and is only accessible by jobs from permitted sessions. Redundancy pool systems are filtered based on system version matching: * Systems must align with the local session's cluster version. * Cluster administrators must maintain version consistency across all session systems. * If a local session contains a system with version 2.4.1, for example, the redundancy pool will select systems with the same version. ### Create Redundancy Pool To create a redundancy pool, run the following command: ```bash theme={null} csctl session create --redundant ``` Then enable the pool: ```bash theme={null} # enable pool-a/pool-b as qa-master's redundancy csctl session update --redundancy-sessions= # clear qa-master's redundancy csctl session update --redundancy-sessions="" ``` To list all sessions in redundant mode: ```bash theme={null} # list all sessions in redundant mode only csctl session list --redundant NAME SYSTEMS NODEGROUPS CRD-NODES REDUNDANCY LAST-ACTIVE test1 0 0 0 *redundant >7 days test2 0 0 0 *redundant >7 days ``` ## Export Logs To download logs for a specific job: ```Bash theme={null} csctl log-export [-b] ``` with optional flags: | Flag | Default Value | Description | | - | - | - | | -b, –binaries | False | Include binary debugging artifacts | | -h, –help | | Informative message for log-export | For example: ```Bash theme={null} csctl log-export wsjob-example-0 Gathering log data within cluster... Starting a fresh download of log archive. Downloaded 0.55 MB. Logs archive: ./wsjob-example-0.zip ``` These logs are useful when debugging a job failure with Cerebras support. ## Worker SSD Cache To speed up the process of large amount of input data, we allow the users to stage their data in the worker nodes’ local SSD cache. This cache is shared among different users. ### Get Worker Cache Usage Use this command to obtain the current worker cache usage on each worker node: ```Bash theme={null} csctl get worker-cache NODE DISK USAGE worker-01 57.86% worker-02 50.84% worker-03 49.47% worker-04 63.56% worker-05 63.56% worker-06 63.71% worker-07 63.22% worker-09 65.80% ``` ### Clear Worker Cache If the cache is full, use the clear command to delete the contents of all caches on all nodes. ```Bash theme={null} csctl get worker-cache Worker caches cleared successfully ``` ## Cluster Status Check the status and system load of all CS-X systems and all cluster nodes: ```Bash theme={null} csctl get cluster ``` In this table, note that the `CPU` and `MEM` columns are only relevant for nodes, and `system-in-use` is only relevant for CS-X systems. The `CPU` percentage is scaled so that 100% indicates that all CPU cores are fully utilized. For example: ```Bash theme={null} csctl get cluster NAME TYPE CPU MEM SYSTEM-IN-USE JOBID JOBLABELS STATE NOTES systemf103 system n/a n/a InUse wsjob-jcvs23zpsxopvu9ymd2e5u wsjob-label= ok systemf116 system n/a n/a InUse wsjob-jcvs23zpsxopvu9ymd2e5u wsjob-label= ok cs-swx001-sx-sr18 broadcastreduce 22.17% 14.20% n/a n/a ok cs-wse002-mg-sr01 management 3.23% 9.45% n/a n/a ok cs-wse005-mx-sr04 memory 13.00% 12.93% n/a n/a ok ``` You can filter the output with the following options: | Flag | Description | | - | - | | -e, -error-only | Only show nodes/systems in an error state | | -n, -node-only | Only show nodes, omit the system list | | -s, -system-only | Only show CS-X systems, omit the node list | # Grafana Dashboards Source: https://training-docs.cerebras.ai/rel-2.5.0/cluster-monitoring/cerebras-job-scheduling-and-monitoring/cluster-monitoring-with-grafana Use Grafana to monitor your Cerebras cluster. Cerebras provides multiple [Grafana](https://grafana.com/docs/grafana/latest/introduction/) dashboards to help you monitor your cluster. Depending on your role, you may see some or all of the following dashboards described here. ## Cluster Admin Dashboards These dashboards are intended for administrators and cluster operators. You’ll see a cluster-wide view of available resources (CSx systems, nodes, switches, links) and their health. Additionally, these dashboards highlight cluster problems at a glance, categorizing them as errors (requiring immediate attention) or warnings (potential issues). Click on resource links to view a resources’ respective dashboard with associated metrics. ## Session Admin Dashboards These dashboards are intended for session owners who need to monitor the utilization and health of a session’s resources and job statuses. You’ll see a session-specific view of the job queue, available resources (CSx systems, nodes, switches, links), and their health. Click on resource links to navigate to specific Resource Details dashboards or Job Admin dashboards to access detailed metrics and job status info. ## Job Admin Dashboards These dashboards are intended for users who want to monitor the status of a job and troubleshoot, if needed. You’ll see a single job in the dashboard with metrics on system utilization and the resources in use. The Job Debug dashboard highlights potential causes of failures and the Job Network Debug dashboard drills down on network resources in use by the job. Click on resource links to navigate to Resource Details dashboards and their associated metrics. ## Resource Details Dashboards These dashboards are intended for administrators and cluster operators who want to view specific cluster resources and the ports/links that connect them. You'll see detailed metrics for cluster resources including CSx systems, nodes, servers, and connecting ports. The metrics cover CPU utilization, memory availability, thermal readings, network performance, link states, and device error counters. ## Access Grafana Ensure you have access to the user node in the Cerebras Wafer-Scale cluster. If you encounter system configuration issues, contact Cerebras Support. ### Set Up Port Forwarding Run the following command to start a port-forwarding SSH session through the user node from your machine: ```bash theme={null} ssh -L 8443:grafana..:443 myUser@usernode ``` > [!NOTE] > > This command forwards traffic through local port `8443`. You can use any unoccupied port on your machine. ### Get Access Credentials 1. Ask your system administrator to set up the Grafana database. URLs follow this format: `grafana..`. For example: `grafana.mb-systemf102.cerebras.com`. 2. Obtain authentication credentials (username and password) from your system administrator. ### Add the Grafana TLS Certificate The Grafana TLS certificate is located at `/opt/cerebras/certs/grafana_tls.crt` on the user node. This certificate is copied during the user node installation. Download it to your local machine and add it to your browser’s keychain. #### On Chrome with MacOS 1. Open **Preferences** > **Privacy and Security** > **Security** > **Manage Certificates**. 2. Add `grafana-tls.crt` to the **System** keychain and set it to **Always Trust**. ### Update the Hosts File Edit your local machine’s `/etc/hosts` file to point the user node’s IP address to Grafana: ```bash theme={null} grafana.. ``` ### Open Grafana Navigate to the Grafana dashboards using the following URL: ```bash theme={null} https://grafana.. ``` # Job Priority Source: https://training-docs.cerebras.ai/rel-2.5.0/cluster-monitoring/cerebras-job-scheduling-and-monitoring/job-priority Learn how jobs are prioritized on a Cerebras cluster. Job scheduling is determined by assigned priorities rather than submission time. Jobs are categorized into four priority buckets, ranging from P0 (highest) to P3 (lowest). Within each bucket, jobs are ranked by numerical priority values, where lower numbers indicate higher priority. Scheduling follows these rankings within designated queues. ## Submit Jobs with Priority Users can specify a job priority at submission using the `--job_priority` flag. For example: ```Bash theme={null} cszoo fit params_model.yaml [additional-args] --job_priority p1 ``` Valid inputs are p1, p2, and p3, corresponding to default values of 199, 299, and 399, respectively. If unspecified, jobs default to P2 (299). Learn more about the additional arguments for launching jobs [here](../fundamentals/launch-your-job). ### Update Job Priority Users can view and adjust a job’s priority post-submission using the [csctl tool](../../cluster-monitoring/cerebras-job-scheduling-and-monitoring/cli-for-job-monitoring-csctl#update-job-priority). > [!NOTE] > > * Only admin users and users with the same GID can modify a job’s priority. > > * Only admin users can access the P0 bucket (0 to 99). > > * Completed jobs cannot have their priorities updated. ### Monitoring Job Priorities Use the [csctl tool](../cluster-monitoring/cerebras-job-scheduling-and-monitoring/cli-for-job-monitoring-csctl) to view job priorities: ```Bash theme={null} cstcl get jobs ``` When listing jobs, you will see both priority values and their corresponding buckets. Jobs are first sorted by priority and then by age. Higher-priority jobs appear first, and within the same priority level, newer jobs are listed before older ones. ### Priority Continuity Jobs stemming from the same invocation inherit the workflow’s priority. Updating a workflow’s priority affects all associated pending and subsequent jobs, ensuring consistent priority across a workflow. ## Additional usage examples Update a job’s priority to a different bucket: ```Bash theme={null} $ csctl job set-priority wsjob-xxxxxx -n mynamespace p2 ``` This updates the job’s priority to P2. Confirmation is displayed: ```Bash theme={null} successfully updated wsjob-jv58f5mb95kwpe5hwuujrk job priority to p2 ``` List jobs with their priorities: ```Bash theme={null} $ csctl job list -a ``` Displays a list of jobs along with details such as type, priority, age, duration, phase, system, user, labels, and dashboard status. For example, it shows that: ```Bash theme={null} NAME TYPE PRIORITY AGE DURATION PHASE SYSTEMS USER LABELS DASHBOARD job-operator/wsjob-jv58f5mb95kwpe5hwuujrk execute P2 (200) 3h56m 88s SUCCEEDED kapi-1 myuser wsjob-label=test grafana not deployed job-operator/wsjob-2ercynhxb44ajhg4qn9bem compile P1 (150) 3h58m 2m21s FAILED myuser wsjob-label=test grafana not deployed ``` # Cerebras Wafer Scale Cluster Source: https://training-docs.cerebras.ai/rel-2.5.0/concepts/cerebras-wafer-scale-cluster The Cerebras [Wafer-Scale Cluster](https://www.cerebras.net/product-cluster/) is meticulously engineered to enable the training of neural networks with remarkably efficient linear scaling across millions of cores, all without the complexities of traditional distributed computing. ![](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/concepts/topology-of-weight-streaming-on-wsc.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=31be5d2fe94cf17479f4a735110caef8) Fig. 1: Topology of Cerebras Wafer-Scale Cluster ## Key Components ### CS-3 Systems The [CS-3 systems](https://www.cerebras.net/product-system/) represents the latest advancement in our lineup, incorporating the innovative WSE-3 (Wafer-Scale Engine 3) to deliver cutting-edge performance. Building on the user-friendly experience of its predecessor, the CS-2, the CS-3 significantly enhances computational efficiency and performance. This next-gen system introduces a novel instruction set architecture and boosts the SIMD (Single Instruction, Multiple Data) width, providing more parallel processing power. Additionally, it expands the core count by 20% and enhances the ingress/egress bandwidth by 30%, enabling faster data processing and transfer rates. Compatibility and performance testing are a cornerstone of the CS-3’s development. All models available in the Model Zoo have been verified for functionality on the CS-3 platform. Furthermore, a selection of key models, including GPT-2, GPT-3, LLaMA, Falcon, BTLM, GPT-J, GPT-NeoX, T5, BERT, and PaLI have undergone rigorous testing to ensure both convergence and performance are optimized for the CS-3, guaranteeing a seamless and efficient user experience. You can find more detailed information in the [WSE-3 datasheet](https://8968533.fs1.hubspotusercontent-na1.net/hubfs/8968533/Datasheets/WSE-3%20Datasheet.pdf) and explore [CS-3](https://www.cerebras.net/product-system/). ### MemoryX Technology [MemoryX technology](https://www.cerebras.net/blog/announcing-the-cerebras-architecture-for-extreme-scale-ai/) serves as the storage and intelligent streaming solution for a model’s weights, ensuring efficient and timely access for the CS-X systems. ### SwarmX Technology [SwarmX technology](https://www.cerebras.net/blog/announcing-the-cerebras-architecture-for-extreme-scale-ai/) plays a pivotal role in integrating multiple CS-X nodes into a unified Cerebras cluster. These nodes collaborate seamlessly in training a single model. SwarmX handles the broadcast of weights from MemoryX to the entire cluster and effectively reduces (sums) gradients in the opposite direction, contributing to efficient training processes. ### Input Preprocessing Servers Input Preprocessing servers handle the critical task of preprocessing training data, ensuring that it is appropriately prepared before being dispatched to the CS-X systems. This preprocessing step is vital for training, inference, and evaluation. ### Management Servers Management servers are responsible for orchestrating and scheduling the cluster's resources, ensuring efficient utilization and coordination among all components in the Cerebras cluster. They play a key role in optimizing the cluster's performance and resource allocation. ## Working with the Cerebras Cluster After developing your code, you can initiate the process of submitting it for both training and evaluation from a user node. It’s important to note that the user node operates independently from the cluster and connects to the Cerebras cluster through the management server, as illustrated in Fig. 1 above. The management server is responsible for handling all resource scheduling. Therefore, your main task is to specify the number of CS-X systems you wish to allocate for either training or evaluation. This enables you to efficiently utilize the Cerebras cluster’s resources without directly managing the intricacies of cluster allocation. For documentation related to the installation and administration of the Cerebras Wafer-Scale cluster, visit Cerebras deployment documentation. # Weight Streaming Execution Source: https://training-docs.cerebras.ai/rel-2.5.0/concepts/weight-streaming-execution The execution mode pertains to the manner in which the Cerebras runtime deploys your neural network model onto the Cerebras Wafer-Scale Engine (WSE). Within the Cerebras Wafer-Scale Cluster, there exists support for the Weight Streaming Mode. In this particular mode, the neural network model is loaded one layer at a time. This layer-by-layer approach is employed when working with expansive models, specifically those in which the weight parameters of a single layer can fit within memory, yet the entirety of the model as a whole cannot. ![](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/concepts/cs-exec-mode-ws-computation.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=a9aaa8f328516a6837d7616c4b32fe50) Fig. 1: Weight Streaming Mode To demonstrate the functioning of Weight Streaming, let’s use the following example of a 3-layer FC-MNIST network: ![](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/concepts/cs-exec-mode-3l-fcmnist.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=d9f71aa68829440a10a39dc806d828c3) Fig. 2: Three-layer FC-MNIST Network ## Weight Streaming Execution during runtime During runtime, the Weight Streaming process unfolds as depicted in **Fig. 3** below. At each step, one layer is loaded onto the Cerebras Wafer-Scale Engine (WSE). The weight data flows from the MemoryX server to the WSE during the forward propagation phase. In the subsequent backpropagation phase, the weights are once again streamed from MemoryX to the WSE. Here on the WSE, weight gradients are computed, and then they are streamed from the WSE to MemoryX for storage. These weight gradients are vital for the learning process, during which the weights are adjusted using the weight gradient in conjunction with the learning algorithm. ![](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/concepts/cs-exec-mode-ws-execution.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=7ec1b8cf0250ba4aee43431393c5c0b2) Fig.3: Weight Streaming Execution Mode ### Compilation The Cerebras compiler plays a crucial role by extracting the operation graph from the code and aligning these operations with the compatible kernels within the Cerebras Software Platform. Each such matched kernel corresponds to a layer in the network’s dataflow graph. You can visualize a mathematical representation of these layers in **Fig. 4**. Should you wish to inspect the outcome of this preliminary compilation phase, you can utilize the --validate\_only flag. The Cerebras compiler strategically plans the mapping of one kernel or layer at a time onto the entire Cerebras Wafer-Scale Engine (WSE), initially for the forward propagation and subsequently for the backward propagation passes. In the event that multiple CS-X systems are requested within the Cerebras Wafer-Scale cluster, the same mapping is employed for every layer across all CS-X systems. For those interested in precompilation, the --compile\_only flag can be employed for this purpose. ![](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/concepts/cs-exec-mode-fcmnist-math.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=2d5c1d0fb58f33561975c8e853508dfb) Fig. 4: Mathematical representation of example network showing color-coded layers and the activations flowing from one layer to the next layer. ### Training During the forward propagation phase, as illustrated in **Fig. 5**: * Layer 1 is the first to be loaded onto the WSE. Input pre-processing servers handle the processing and streaming of training data to the WSE, while MemoryX streams the weights of layer 1 into the WSE. If there’s a request for multiple CS-X in the training job, SwarmX broadcasts the weights from MemoryX to all the WSEs. The batch of training samples is divided into equally sized subsets, or shards, with each shard directed to a respective CS-X. This technique is known as data parallelism. * Each WSE simultaneously performs the forward computation for layer 1 in parallel with the others. * The calculated activations for layer 1 are retained in the WSE’s memory. * Subsequently, MemoryX broadcasts the weights of layer 2 to the WSEs. * Each WSE conducts the forward computations for layer 2, utilizing its stored activations from layer 1. * This same process is repeated for layer 3. * In this manner, the forward computation for each layer is carried out by employing the previously computed activations from the preceding layer. Additionally, the calculated activations for the current layer are stored in the WSE’s memory for use by the next loaded layer. * At the loss layer, the actual labels from the training data are employed to compute the network loss delta, which represents the gradient of the scalar loss concerning the activation of the output layer (layer 3). This loss delta plays a crucial role in calculating layer-by-layer deltas and weight gradients during the subsequent backward pass. ![](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/concepts/cs-exec-mode-ws-fwd.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=7e69f72ef57b75337bbd70f1acbae7b0) Fig.5: Schematic representation of the forward propagation in Weight Streaming Mode. In the backward propagation phase, as illustrated in **Fig. 6**: * The weights of layer three are broadcast from MemoryX to the WSEs, where the gradient and delta computations for layer three are performed. It’s worth noting that, in practice, the weights of this output layer can be retained to save time. * The gradients for layer three are then streamed out of the WSEs to SwarmX. SwarmX aggregates (sums together) the gradients from multiple WSEs and presents this sum to MemoryX. MemoryX employs this aggregate gradient within the learning algorithm to update its stored copy of the layer weights. * Subsequently, the weights of layer two are streamed from MemoryX to the WSE, and the WSE performs similar gradient and delta computations for layer two. The layer two gradients are then streamed out of the WSE to MemoryX, where weight updates take place. If there’s a request for multiple CS-X in the training job, SwarmX broadcasts the weights from MemoryX to all the WSEs and consolidates the gradient updates from the WSEs to MemoryX. * This backward pass sequence continues until the gradients for layer one are streamed out to MemoryX, where weight updates occur. Following this, the forward pass for the next training batch commences with the updated weights. ![](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/concepts/cs-exec-mode-ws-bwd.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=e2ff57952e16ab5c7dd47cea8ebb5984) Fig. 6: Schematic representation of the backward propagation in Weight Streaming Mode. Meanwhile, within the user node: * As the loss values are calculated on the WSEs, SwarmX consolidates them and then transmits the results to the user node. * Additionally, at specified intervals, all the weights can be retrieved from MemoryX and transferred to the user node for checkpoint purposes. # Writing a Custom Training Loop Source: https://training-docs.cerebras.ai/rel-2.5.0/cs-torch/writing-a-custom-training-loop Learn how to write a custom training loop for a simple, fully connected model on the MNIST dataset. Our typical workflow involves using a training script provided in the Cerebras Model Zoo. However, if that training loop is insufficient for your model needs, you may write your own training loop using the Cerebras PyTorch API. > [!NOTE] > > The following steps will only take you through the absolute minimum code required to run a simple, small model on the Cerebras Wafer Scale Cluster. To extend the script to feature things like [learning rate scheduling](../cs-torch/writing-a-custom-training-loop/learning-rate-scheduling), [gradient scaling](../cs-torch/writing-a-custom-training-loop/gradient-scaling), etc. please continue to the [further reading](#further-reading) section to learn more about these topics. ## Prerequisites You have installed the [cerebras.pytorch package](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cstorch-class-docs) in your environment. ## Validate the Package Installation Run the following command to validate that [cerebras.pytorch package](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cstorch-class-docs) is installed correctly: ```python theme={null} import cerebras.pytorch as cstorch ``` > [!NOTE] > > From here on, we will be using `cstorch` as the alias for `cerebras.pytorch` ## Configure the Wafer Scale Cluster To configure the Cerebras Wafer-Scale cluster, construct a [`ClusterConfig`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html?highlight=clusterconfig#cerebras.pytorch.distributed.ClusterConfig) object, then use that to construct a [`backend`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html?highlight=clusterconfig#cerebras.pytorch.backend) object: ```python theme={null} cluster_config = cstorch.distributed.ClusterConfig( max_wgt_servers=1, max_act_per_csx=1, num_workers_per_csx=1, ) backend = cstorch.backend( "CSX", cluster_config=cluster_config, ) ``` See the class documentation for [`ClusterConfig`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html?highlight=clusterconfig#cerebras.pytorch.distributed.ClusterConfig) to view all configurable options. > [!NOTE] > > Most options have reasonable defaults and do not need to be changed. ## Define Your Model When using the Cerebras PyTorch API, define your model in the same way you would in a Vanilla PyTorch workflow: ```python theme={null} import torch import torch.nn.functional as F class Model(torch.nn.Module): def __init__(self): super().__init__() self.fc1 = torch.nn.Linear(784, 256) self.fc2 = torch.nn.Linear(256, 10) def forward(self, inputs): inputs = torch.flatten(inputs, 1) outputs = F.relu(self.fc1(inputs)) return F.relu(self.fc2(outputs)) model = Model() ``` > [!NOTE] > > Weight initialization for large models can cause out-of-memory errors. Not only that, but initializing extremely large models eagerly can be very slow. See the page on [Efficient weight initialization](../cs-torch/writing-a-custom-training-loop/efficient-weight-initialization) to see how to work around this issue. ## Compile Your Model Once the model has been instantiated, compile the model by calling the [`cerebras.pytorch.compile`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.compile "cerebras.pytorch.compile"), for example: ```python theme={null} compiled_model = cstorch.compile(model, backend) ``` > [!NOTE] > > The call to `cstorch.compile` doesn’t actually compile the model. Similar to `torch.compile` it only prepares the model for compilation. Compilation only happens after the first iteration, once the input shapes are known. ## Optimize Model Parameters To optimize model parameters using the Cerebras Wafer-Scale cluster, you must use a Cerebras-compliant optimizer. There are exact drop-in replacements for all commonly used optimizers available in [cerebras.pytorch.optim](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cstorch-optim-class-docs), for example: ```python theme={null} optimizer = cstorch.optim.SGD(model.parameters(), lr=0.001, momentum=0.9) ``` > [!NOTE] > > If you are interested in writing your own custom Cerebras-compliant optimizer, see [Writing Custom Optimizers](../cs-torch/writing-a-custom-training-loop/writing-custom-optimizers). ## Dataloaders To send data to the Wafer-Scale cluster, wrap your PyTorch dataloader with [`cerebras.pytorch.utils.data.DataLoader`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.utils.data.DataLoader). For example: ```python theme={null} def get_torch_dataloader(batch_size, train): from torchvision import datasets, transforms train_dataset = datasets.MNIST( "/path/to/data", # change this path train=train, download=True, transform=transforms.Compose( [ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)), ] ), target_transform=transforms.Lambda( lambda x: torch.as_tensor(x, dtype=torch.int32) ), ) return torch.utils.data.DataLoader( train_dataset, batch_size=batch_size, shuffle=True ) training_dataloader = cstorch.utils.data.DataLoader( get_torch_dataloader, batch_size=64, train=True ) ``` The Cerebras PyTorch dataloader requires a callable that generates a PyTorch dataloader. This approach ensures that each worker can independently create its own dataloader instance, optimizing distributed parallelism. ## Define the Training Step To execute a single training iteration on the Wafer-Scale Cluster, you first need to capture all operations intended to run on the cluster. Do this by defining a function that includes all actions for a single training iteration and decorating it with [`cerebras.pytorch.trace`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.trace). For example: ```python theme={null} loss_fn = torch.nn.CrossEntropyLoss() @cstorch.trace def training_step(inputs, targets): outputs = compiled_model(inputs) loss = loss_fn(outputs, targets) loss.backward() optimizer.step() optimizer.zero_grad() return loss ``` This function is traced and sent to the cluster for compilation and execution. ## Define an Execution To program an execution run on the Cerebras Wafer-Scale cluster, define an instance of the [`cerebras.pytorch.utils.data.DataExecutor`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.utils.data.DataExecutor). For example: ```python theme={null} train_executor = cstorch.utils.data.DataExecutor( training_dataloader, num_steps=100, checkpoint_steps=50, ) ``` It takes in the Cerebras PyTorch dataloader that will be used during the run, the total number of steps to run for, as well as the interval at which checkpoints will be taken. ## Train Your Model Once the above is defined, you can iterate through the executor to train your model. ```python theme={null} @cstorch.step_closure def print_loss(mode, loss: torch.Tensor, step: int): print(f"{mode} Loss {step}: {loss.item()}") @cstorch.checkpoint_closure def save_checkpoint(step): cstorch.save( { "model": model.state_dict(), "optimizer": optimizer.state_dict(), }, f"checkpoint_{step}.mdl", ) global_step = 0 for inputs, targets in train_executor: loss = training_step(inputs, targets) print_loss("Training", loss, global_step) global_step += 1 save_checkpoint(global_step) ``` > [!NOTE] > > * Notice how the loss was passed into a function decorated by `step_closure`. This is required to retrieve the loss value from the cluster before it can be used. See the page on [step closures](../cs-torch/writing-a-custom-training-loop/step-closures) for more details. > * Also, notice how checkpoints are saved inside a function decorated by [`checkpoint_closure`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.checkpoint_closure). This is required to retrieve the model weights and optimizer state back from the cluster before it can be saved. Please see the page on [saving checkpoints](../cs-torch/writing-a-custom-training-loop/saving-loading-checkpoints#saving-loading-checkpoint). ## Putting It All Together Combining all of the above steps, you create a super minimal training script for a simple, fully connected model training on the MNIST dataset: ```python theme={null} # Import the Cerebras PyTorch module import cerebras.pytorch as cstorch import torch import torch.nn.functional as F def main(): # Define a model class Model(torch.nn.Module): def __init__(self): super().__init__() self.fc1 = torch.nn.Linear(784, 256) self.fc2 = torch.nn.Linear(256, 10) def forward(self, inputs): inputs = torch.flatten(inputs, 1) outputs = F.relu(self.fc1(inputs)) return F.relu(self.fc2(outputs)) backend = cstorch.backend( "CSX", cluster_config=cstorch.distributed.ClusterConfig( max_wgt_servers=1, max_act_per_csx=1, num_workers_per_csx=1, ), ) model = Model() # Compile the model compiled_model = cstorch.compile(model, backend=backend) # Define an optimizer optimizer = cstorch.optim.SGD(model.parameters(), lr=0.001, momentum=0.9) # Define a data loader def get_torch_dataloader(batch_size, train): from torchvision import datasets, transforms train_dataset = datasets.MNIST( "/path/to/data", # change this path train=train, download=True, transform=transforms.Compose( [ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)), ] ), target_transform=transforms.Lambda( lambda x: torch.as_tensor(x, dtype=torch.int32) ), ) return torch.utils.data.DataLoader( train_dataset, batch_size=batch_size, shuffle=True ) training_dataloader = cstorch.utils.data.DataLoader( get_torch_dataloader, batch_size=64, train=True ) # Define the training step loss_fn = torch.nn.CrossEntropyLoss() @cstorch.trace def training_step(inputs, targets): outputs = compiled_model(inputs) loss = loss_fn(outputs, targets) loss.backward() optimizer.step() optimizer.zero_grad() return loss @cstorch.step_closure def print_loss(loss: torch.Tensor, step: int): print(f"Train Loss {step}: {loss.item()}") @cstorch.checkpoint_closure def save_checkpoint(step): cstorch.save( { "model": model.state_dict(), "optimizer": optimizer.state_dict(), }, f"checkpoint_{step}.mdl", ) global_step = 0 train_executor = cstorch.utils.data.DataExecutor( training_dataloader, num_steps=100, checkpoint_steps=50, ) model.train() for inputs, targets in train_executor: loss = training_step(inputs, targets) print_loss(loss, global_step) global_step += 1 save_checkpoint(global_step) if __name__ == "__main__": main() ``` ## Further Reading * [Step Closures](../cs-torch/writing-a-custom-training-loop/step-closures) * [Saving/Loading Checkpoints](../cs-torch/writing-a-custom-training-loop/saving-loading-checkpoints) * [Efficient Weight Initialization](../cs-torch/writing-a-custom-training-loop/efficient-weight-initialization) * [Writing Custom Optimizers](../cs-torch/writing-a-custom-training-loop/writing-custom-optimizers) * [Learning Rate Scheduling](../cs-torch/writing-a-custom-training-loop/learning-rate-scheduling) * [Gradient Scaling](../cs-torch/writing-a-custom-training-loop/gradient-scaling) * [Sparsifying Models](../cs-torch/writing-a-custom-training-loop/sparsifying-models) * [Restartable Dataloaders](../cs-torch/writing-a-custom-training-loop/restartable-dataloaders) * [Profiling the Executor](../cs-torch/writing-a-custom-training-loop/profiling-the-executor) * [Evaluation Metrics](../cs-torch/writing-a-custom-training-loop/evaluation-metrics) # Efficient Weight Initialization Source: https://training-docs.cerebras.ai/rel-2.5.0/cs-torch/writing-a-custom-training-loop/efficient-weight-initialization Learn how to enhance weight initialization efficiency and speed for large-scale models using advanced Cerebras techniques. This guide explores a method to initialize model parameters more efficiently by leveraging Cerebras’ hardware acceleration. Typically, initializing parameters on a CPU can be slow for large models and might lead to memory constraints - specifically, there’s a risk that parameters won’t fit within the available RAM, leading to potential overflow into swap memory or, in some cases, complete failure to allocate the necessary memory. To mitigate these issues, we introduce an approach using a [`cerebras.pytorch.backend`](https://docs.cerebras.net/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.backend "cerebras.pytorch.backend") instance, facilitating the parameter initialization process on a Cerebras device, similar to how one would use a `torch.device`. For example: ```python theme={null} # Initialize the Cerebras backend for efficient processing. backend = cstorch.backend("CSX") # Use the backend's device context manager for initializing the model. with backend.device: model = Model() # Compile the model using the Cerebras backend for optimized execution. compiled_model = cstorch.compile(model, backend) ``` This method automatically moves the parameters to the Cerebras device, optimizing memory usage and enhancing initialization speed. This frees up memory for subsequent parameters and keeps the overall memory usage low. This approach simplifies the process of achieving more efficient weight initialization. For a deeper understanding of the underlying mechanics, refer to the following subsections. ## Lazy Weight Initialization Lazy Initialization enhances the model initialization process by tracing a model’s initialization. It also removes redundant computations that occur before initialization, significantly decreasing the time to achieve the first loss. This functionality transforms the way models are initialized, fostering a more efficient and resource-aware approach to training. To invoke lazy initialization, proceed with the following steps: ```python theme={null} # Initialize the Cerebras backend. backend = cstorch.backend("CSX") # Initialize the model within the backend's context for lazy initialization. with backend.device: model = Model() ``` Initializing the model from within the backend’s device context manager allows us to fully capture the initialization graph to compute at a later time. Doing so creates many opportunities to optimize the initialization, such as: * Rapid weight initialization and initiate the model compilation process * Minimizes the underlying computational efforts * Enhances the parallelization of weight initialization computations * Substantially reduces overall memory usage * Reduces the number of file write operations needed Consequently, lazy initialization is the default setting, automatically applied when a model is initialized within the backend device’s context manager. If you encounter numerical or convergence issues, you can disable this feature to see if its the model initialization that is the cause of the issues: ```python theme={null} backend.device.config.lazy_initialization = False ``` Disabling lazy initialization shifts the initialization scheme closer to eager model initialization - which substantially lengthens the time needed to initialize the model and delays the receipt of the first result from the cluster. To learn more about how the benefits described above are achieved, read the following subsections. ### Parallelizing Weight Initialization Upon completing the tracing of the model’s initialization, for efficiency gains we divide the weight graphs into distinct subgraphs that can be executed concurrently. Since they do not have any dependencies between them, they can be executed in parallel. By default, four initialization subgraphs are executed in parallel. This default was chosen empirically using data from many different experiments. To change the number of subgraphs that are initialized at once, set the following: ```python theme={null} # Set the maximum number of parallel subgraphs for initialization. backend.device.config.max_async_parallel_compute = 4 ``` Increasing the parallelization may cause out-of-memory issues. In the worst case, we could potentially be initializing `N` extremely large weights at once. This is typically unlikely as smaller weights outnumber large ones, if Out-of-Memory issues occur, reducing the maximum parallelization level using the configuration variable might help. #### Deterministic Pseudo-Random Weight Initialization When initializing weights in parallel using a pseudo-random number generator, the simultaneous initialization of multiple weights involving random sampling brings up concerns regarding the determinism of weight initialization. The adopted solution is to assign a unique pseudo-random number generator to each random sampling operation. These generators are individually seeded using the default random number generator, allowing for deterministic seeding with `torch.manual_seed(seed)`. Example transformation for deterministic behavior: ```python theme={null} # Initialize a linear layer. model = torch.nn.Linear(15, 10) # Assign a unique generator for deterministic random initialization. with torch.no_grad(): model.weight.uniform_() ``` We inject a generator so that what is effectively getting executed is: ```python theme={null} model = torch.nn.Linear(15, 10) with torch.no_grad(): g = torch.Generator() g.manual_seed(torch.randint(..., generator=torch.default_generator)) model.weight.uniform_(generator=g) ``` This is done for every single random operator in the initialization graph, thus making each initialization subgraph completely independent from one another. Consequently, this approach guarantees that even when multiple weights are initialized in parallel, the outcomes are deterministic. ### Optimizing Weight Initialization After capturing and dividing the initialization graph into subgraphs, there’s an opportunity to refine and optimize these subgraphs prior to their execution. For example, take the initialization of the following weight: ```python theme={null} # Define a linear layer. model = torch.nn.Linear(15, 10) with torch.no_grad(): # Normal initialization. model.weight.normal_() # Uniform initialization model.weight.uniform_() ``` The call to `normal_` is rendered redundant as the very next call to `uniform_` will overwrite all the values in `model.weight` anyways. Eliminating the call to `normal_` won’t affect the final result, maintaining the same outcomes while streamlining the process. By default, this optimization process prunes a specific set of operations known to overwrite all the values of the input tensor. These operations include, but are not limited to: * `fill` * `normal` * `random` * `uniform` * `zero` If you come across a situation where the numerical values, like the weight distribution, do not align with the expected outcome, turn off the initialization optimization by configuring the following settings: ```python theme={null} # Disable initialization optimization. backend.device.config.optimize_initialization = False ``` ## Implementation Notes 1. Ensure that the Cerebras backend is correctly initialized and accessible. 2. When working with large models, monitor memory usage to prevent overflow. 3. Know which operations are pruned by default and how this affects the initialization process. ## Best Practices 1. While lazy initialization can speed up the setup process, be aware of its implications and switch to eager initialization if you face issues related to model convergence or performance. 2. Validate the initialization’s impact on model training to ensure that efficiency gains don’t compromise model performance. 3. Ensure that your system has enough memory to support the chosen level of parallelization without running into out-of-memory issues. # Evaluation Metrics Source: https://training-docs.cerebras.ai/rel-2.5.0/cs-torch/writing-a-custom-training-loop/evaluation-metrics Learn to use and create metrics in Cerebras for evaluating PyTorch models, including predefined metrics like AccuracyMetric and custom metrics tailored to specific evaluation needs. We provide Cerebras-compatible metrics that can be used during evaluation to measure how well the model has been trained. These metrics can be found in the [metrics.Metric](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/metrics.html#metrics) module. For example: ```python theme={null} model = Model() compiled_model = cstorch.compile(model, backend) accuracy = cstorch.metrics.AccuracyMetric("accuracy") @cstorch.trace def eval_step(batch): inputs, targets = batch outputs = compiled_model(inputs) accuracy( labels=targets.clone(), predictions=outputs.argmax(-1).int(), ) ... for batch in executor: ... # Log accumulated eval metric print(f"Accuracy: {float(accuracy)}") ``` ## Writing Custom Metrics To define a Cerebras compliant metrics, create a subclass of [`cerebras.pytorch.metrics.Metric`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/metrics.html#cerebras.pytorch.metrics.Metric "cerebras.pytorch.metrics.Metric"). For example, ```python theme={null} class CustomMetric(cstorch.metrics.Metric): def __init__(self, name: str): super().__init__(name) ... ... def reset(self): pass def update(self, *args, **kwargs): ... def compute(self): ... ``` As can be seen in the above example, the base [`Metric`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/metrics.html#cerebras.pytorch.metrics.Metric "cerebras.pytorch.metrics.Metric") class expects one argument. Namely, the metric name. In addition, there are three abstract methods that must be overridden: * [`reset`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/metrics.html#cerebras.pytorch.metrics.Metric.reset "cerebras.pytorch.metrics.Metric.reset") This method resets (or defines if its the first time its called) the metrics’ internal state.States can be registered via calls to [`register_state`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/metrics.html#cerebras.pytorch.metrics.Metric.register_state "cerebras.pytorch.metrics.Metric.register_state") * [`update`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/metrics.html#cerebras.pytorch.metrics.Metric.update "cerebras.pytorch.metrics.Metric.update") This method is used to update the metric’s registered states.Note that to remain Cerebras compliant, no tensor may be evaluated/inspected here. The update call is intended to be fully traced. * [`compute`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/metrics.html#cerebras.pytorch.metrics.Metric.compute "cerebras.pytorch.metrics.Metric.compute") This method is used to compute the final accumulated metric value using the state that was updated in [`update`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/metrics.html#cerebras.pytorch.metrics.Metric.update) # Gradient Scaling Source: https://training-docs.cerebras.ai/rel-2.5.0/cs-torch/writing-a-custom-training-loop/gradient-scaling Gradient scaling can improve convergence when training models with float16 gradients by minimizing gradient underflow. Please see the [PyTorch docs](https://pytorch.org/docs/stable/amp.html#gradient-scaling) for a more detailed explanation. To facilitate gradient scaling, we introduce a Cerebras-compliant implementation of the AMP GradScaler class found in core PyTorch at [`cerebras.pytorch.amp.GradScaler`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/amp.html#cerebras.pytorch.amp.GradScaler "cerebras.pytorch.amp.GradScaler"). For example: ```python theme={null} grad_scaler = cstorch.amp.GradScaler(loss_scale="dynamic") ``` It is designed to be as similar as possible to the API of the CUDA AMP GradScaler class. Its usage is identical to the usage of the CUDA AMP GradScaler: ```python theme={null} loss: torch.Tensor = ... optimizer.zero_grad() # Scale the loss before calling the backward pass grad_scaler.scale(loss).backward() # Unscales the gradients of the optimizer's assigned params in-place # to facilitate things like gradient clipping grad_scaler.unscale_(optimizer) # (Optional) Global gradient clipping torch.nn.utils.clip_grad_norm_( model.parameters(), 1.0, # max gradient norm ) # Step the optimizer using the grad scaler grad_scaler.step(optimizer) # update the grad scaler once all optimizers have been stepped grad_scaler.update() ``` ### Using Automatic Mixed Precision By default, automatic mixed precision uses `float16`. If you want to use `cbfloat16` or `bfloat16` instead of `float16`, call [`cerebras.pytorch.amp.set_half_dtype`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/amp.html#cerebras.pytorch.amp.set_half_dtype "cerebras.pytorch.amp.set_half_dtype"), e.g. ```python theme={null} cstorch.amp.set_half_dtype("cbfloat16") ``` ### Using a Helper Function for Gradient Scaling We introduce an optional helper function [`cerebras.pytorch.amp.optimizer_step`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/amp.html#cerebras.pytorch.amp.optimizer_step "cerebras.pytorch.amp.optimizer_step") to take care of the details of gradient scaling ```python theme={null} cstorch.amp.optimizer_step( loss, optimizer, grad_scaler, max_gradient_norm=..., # optionally perform gradient clipping by norm max_gradient_val=..., # optional perform gradient clipping by value ) ``` > [!NOTE] > > It is useful for quickly constructing typical examples that use gradient scaling without needing to type up the details or worry about whether the grad scaler is being used correctly. > > This is entirely optional and only covers the basic gradient scaler use case. For more complicated use cases, the grad scaler object must be used explicitly. # Learning Rate Scheduling Source: https://training-docs.cerebras.ai/rel-2.5.0/cs-torch/writing-a-custom-training-loop/learning-rate-scheduling Learn how to write a custom learning rate scheduler. Similar to optimizers, the PyTorch Vanilla learning rate schedulers are incompatible with traced lazy execution. There are exact drop-in replacements for all commonly used learning rate schedulers available in [cerebras.pytorch.optim.lr\_scheduler](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#lr-scheduler-class-docs). For example: ```python theme={null} lr_scheduler = cstorch.optim.lr_scheduler.LinearLR( optimizer, initial_learning_rate=0.01, end_learning_rate=0.0001, total_iters=1000, ) ``` ### Write a Custom Learning Rate Scheduler To define a Cerebras-compliant learning rate scheduler, create a subclass of [`cerebras.pytorch.optim.lr_scheduler.LRScheduler`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.lr_scheduler.LRScheduler). For example: ```python theme={null} class CustomScheduler(cstorch.optim.lr_scheduler.LRScheduler): def __init__(self, optimizer, ...): ... super().__init__(optimizer, total_iters=..., last_epoch=...) ... def _get_closed_form(self) -> torch.Tensor: ... ``` As seen in the above example, the base [`LRScheduler`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.lr_scheduler.LRScheduler "cerebras.pytorch.optim.lr_scheduler.LRScheduler") class expects three arguments: 1. The optimizer whose learning rate is being scheduled 2. The total number of iterations scheduled (optional) 3. The last epoch to start on In addition, the [`_get_closed_form`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.scheduler.Scheduler._get_closed_form) abstract method must be overridden. This method is where the full scheduler is defined in closed form. > [!NOTE] > > Due to the nature of lazy tensor tracing and execution, there may not be any Python level conditions or loops used to dynamically define the control flow. This means that only torch ops (such as `torch.where`) may be used. Moreover, static structures are allowed. For example, a loop with a fixed number of iterations, or a Python conditional that doesn’t involve any torch tensors whose conditional involves only constant variables. This method is expected to return a `torch.Tensor` that represents the full learning rate schedule as a computed tensor. See the existing LR scheduler implementations for examples of how to correctly define the schedule. Once you’ve written your custom LR scheduler, as long as its available in the global scope, you can use it in ModelZoo in a similar way by setting the `scheduler` to be the name of your custom LR schedule class in your params YAML file. # Limitations of Pytorch on Cerebras Source: https://training-docs.cerebras.ai/rel-2.5.0/cs-torch/writing-a-custom-training-loop/limitations-of-pytorch-on-cerebras Developing for the Cerebras Wafer-Scale Cluster requires a different approach to PyTorch programming. The key is to think in terms of static, tensor-based computational graphs rather than dynamic, Python-driven logic. ## Floating Point Precision The Cerebras system supports only mixed-precision training: * Weights are stored as `float32` * Computations use a combination of `float32` and one of: * `cbfloat16` * `bfloat16` * `float16` Precision casts are automatically inserted, so developers don't need to manage them manually. See [numeric precision](../../model-zoo/components/trainer-components/numeric-precision#numeric-precision) for more information on switching between precision optimization levels. > [!NOTE] > > At the moment, our primary focus is on the precision modes we currently offer. While we’re not actively pursuing the support of other precision modes, we remain open to potential developments in this area in the future. ## Ahead-of-Time (AOT) Compilation The Cerebras Wafer-Scale Cluster relies on Ahead-of-Time compilation, which means: * The entire model's execution graph must be traced and compiled before execution * Models run asynchronously * PyTorch receives updates through callback mechanisms called [step closures](../../cs-torch/writing-a-custom-training-loop/step-closures) ## Coding Constraints and Recommendations ### Prioritize Tensor Operations Avoid Python flow control like if statements and loops, as they can lead to unexpected behavior due to incomplete graph capture. Instead, use tensor operations like `torch.where` for conditional logic. The `torch.where` function acts as a tensor-based conditional, equivalent to an if statement but represented within the graph. Avoid any flow control that could cause a different graph. Only tensor operations are traced during execution. So the following code snippet: ```python theme={null} def bad_function(input1: torch.Tensor, input2: torch.Tensor) -> torch.Tensor: global step # regular python int. global is bad for other reasons, but ignore that step += 1 if step < 10: return input1 else: return input2 ``` would behave as if it were: ```python theme={null} def bad_function(input1: torch.Tensor, input2: torch.Tensor) -> torch.Tensor return input1` ``` Tracing captures only the first step’s static graph, necessitating tensor-based control flow. Instead, all operations must be tensors: ```python theme={null} def better_function(input1: torch.Tensor, input2: torch.Tensor, step: torch.Tensor) -> torch.Tensor: step += 1 output = torch.where(step < 10, input1, input2) return output ``` ### Prematurely Fetching Tensor Values During tracing, tensor values are not actually computed. As such, eagerly retrieving the value of tensors is not allowed. You must design your code to avoid accessing tensor values during tracing. For debugging and accessing tensor values, refer to the [Step closures](../../cs-torch/writing-a-custom-training-loop/step-closures) documentation. Look at the following example: ```python theme={null} def bad_function(input1: torch.Tensor, input2: torch.Tensor) -> torch.Tensor: if input1.max() < 0: raise ValueError("input1 must have positive elements!") return input1 + input2 ``` During tracing, the value of `input1.max()` is not known but is required to compute the Python conditional. Hence, this will lead to the following tracing error: ```Bash theme={null} Traceback (most recent call last): File "modelzoo/fc_mnist/pytorch/model.py", line 50, in forward pred_logits = bad_function(self.last_layer(x)) File "modelzoo/fc_mnist/pytorch/model.py", line 11, in bad_function if input1.max() < 0: RuntimeError: The Cerebras backend does not yet support `aten::_local_scalar_dense(Tensor self) -> Scalar` ``` The other commonly used statements that could lead to evaluating tensors are printing, asserting the tensor value, and calling `tensor.to("cpu")`, and calling `tensor.item()`. ### Avoid Decaying Traced Tensors to Scalars Tensors generated during tracing have their values hidden until execution, as the Cerebras WSC compiles the model graph before running it. Certain `torch` operations expect scalar values as arguments, but passing traced tensors to them can lead to unexpected behavior. Always explicitly convert traced tensors to scalars before using them in these contexts. Try restructuring code to avoid traced tensors in scalar operations whenever possible, as explicit conversions can impact performance. Torch operations such as `torch.add` (alpha argument expects a scalar, and not a traced tensor) and `torch.addcdiv` (which expects a scalar) can offer performance benefits. They leverage fused-multiply-add or similar techniques for efficiency. However, remember that they expect true scalar values for certain arguments (e.g., value, alpha): ```python theme={null} output = input.addcdiv(tensor1, tensor2, 3.14) ``` Constants or tensors created outside tracing work as expected, as their values are readily available: ```python theme={null} pi = torch.tensor(3.14, dtype=torch.float16) output = input.addcdiv(tensor1, tensor2, pi) ``` While scalars and external tensors work seamlessly, those generated within traced operations (like learning rate schedules) can cause trouble: ```python theme={null} lrs = torch.where(step > 1000, step.float() * 0.0001, 0.0002) output = input.addcdiv(tensor1, tensor2, lrs) ``` The implicit Tensor > Scalar decay will trigger the `SyncTensor` called outside of MarkStep error and a random value will be used instead. In addition, if this was the only “use” of the lrs tensor, walking the dependency graph of all traced values will show no computation depending on the value of lrs and the entire set of tensor operations will not be lowered and compiled down. ### Pre-Initialize Stateful Tensors The Cerebras WSC compiles the model’s execution graph based on operations observed during the first step, assuming subsequent steps follow the same pattern. Tensors carry state information across steps and are essential for optimizers and other stateful components. The Cerebras WSC tracks the identities of stateful tensors to maintain their values between steps. Initializing stateful tensors within conditional blocks or based on runtime conditions during the first step can lead to issues. Therefore, ensure all stateful tensors are explicitly initialized before tracing begins, even if their initial values might be overwritten later. If a stateful tensor isn’t initialized before tracing begins, it won’t have a registered identity within the system. As a result, the Cerebras WSC won’t recognize it as a persistent tensor that needs to be loop-carried. In each subsequent step, the tensor will be treated as a new tensor and initialized to zero, losing any previously updated values. Instead of being loop-carried, the updated tensor values get misinterpreted as model outputs like predictions or losses. Because the Cerebras WSE compiles the model’s execution graph based on the operations observed during the first step, assuming all subsequent steps will follow the same pattern, any stateful tensors (those that maintain state across steps) must be initialized explicitly before tracing begins. Initializing them conditionally or during runtime within the first step can lead to tracking issues and unexpected behavior and should be avoided: ```python theme={null} class CustomOptimizer(torch.optim.Optimizer): ... def step(self): ... for param_group in self.param_groups: for p in param_group["params"]: if len(self.state[p]) == 0: state[p]["momentum"] = torch.zeros_like(p.grad) state[p]["momentum"].add_(p.grad * 0.001) ... ``` In addition to tracing operations, we also track the “identity” of certain tensors in order to loop-carry state between successive steps of the computation - the updated valued for `state[param]["momentum"]` on step 1 should be fed as the initial value for `state[param]["momentum"]` on step 2 etc. These values are “weights” and kept resident in system memory of some kind (on wafer in pipeline mode, or in the MemoryX/weight hosts in weight streaming). In this case (even disregarding the python flow control), the `state[param]["momemtum"]` has no identity before this first step. Executing the operations recorded by this trace would re-initialize momentum to zero on every single step, with the updated tensor result having no place to be stored (it would be treated as another model output like loss or predictions). ### Optimizer Considerations Following the above guidelines and leveraging the Cerebras optimizer wrapper capabilities, you can seamlessly integrate your PyTorch optimizers with the Cerebras Wafer Scale Cluster. Cerebras optimizer wrapper’s `preinitialize()` function ensures that all stateful tensors within the optimizer, typically stored in its state\_dict, are explicitly initialized before the tracing process begins. This is crucial for Cerebras WSC compatibility. The Cerebras framework automatically calls `preinitialize()` at the appropriate time, simplifying compliance. The function can also be called within the optimizer’s `_init_` method for traditional GPU-based training, providing a flexible implementation. The Cerebras optimizer wrapper injects a traced tensor for `param_group["lr"]` to dynamically implement learning rate schedules based on a traced `global_step tensor`. Passing these traced tensors to operations that expect scalar values can lead to unexpected behavior or errors due to implicit decay attempts. Refactor static graphs by exploring alternative tensor-based implementations or restructuring to avoid non-static graph constructs. ## Learning Rate Scheduler Currently, we do not support the typical PyTorch learning rate scheduler paradigm. A typical PyTorch learning scheduler would compute a learning rate scalar and set the values of the learning rates in the optimizer parameter groups. However, we cannot support this behavior due to the system’s current limitations requiring static graphs. We must specify the entire learning rate schedule as a function of the global step. This means that the learning rate becomes less of a scalar value and more of a tensor that depends on the value of the global step. See [Learning rate scheduling](../../cs-torch/writing-a-custom-training-loop/learning-rate-scheduling) for more details. This also means that any optimizers being used need to be written in a way such that the learning rate is not treated as a scalar value but rather as a tensor. See `cerebras.pytorch.optim.AdamBase` for an example of this. ## Multiple Execution Limitations The cluster configuration is locked in on the first compile job encountered. This means the first compile should be the most resource-intensive job. That is to say, if both training and eval are being performed, training must come before eval. If eval is performed before training, the train compile might fail if the first eval compile didn’t allocate enough resources. This also means [`CSConfig`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.utils.CSConfig) configurations, such as `num_csx` and `num_workers_per_csx` are global across all executions. ### Modifying Stateful Tensors Between Executions Stateful tensors may be modified between executions if a checkpoint was taken on the last step of the previous execution. For example, between a training and evaluation run, changing model parameters or optimizer states for instance is only supported if a checkpoint was taken in the last training step. What this means is that checkpoint steps must be greater than 0 in the data executor: ```python theme={null} train_executor = cstorch.utils.data.DataExecutor( num_steps=1000, checkpoint_steps=100 ) for inputs, targets in train_executor: ... model.fc1.weight.data.mul_(0.9) # This is allowed train_executor = cstorch.utils.data.DataExecutor( num_steps=1000, checkpoint_steps=0 ) for inputs, targets in train_executor: ... model.fc1.weight.data.mul_(0.9) # This is *not* allowed validation_executor = cstorch.utils.data.DataExecutor(...) for step, (inputs, targets) in enumerate(validation_executor): ... ``` > [!NOTE] > > Modifying weights in between executions (even if a checkpoint was taken) is *only* allowed if lazy initialization is enabled. See [Efficient weight initialization](../../cs-torch/writing-a-custom-training-loop/efficient-weight-initialization) for more details. # Per Layer Precision Optimization Level Source: https://training-docs.cerebras.ai/rel-2.5.0/cs-torch/writing-a-custom-training-loop/per-layer-precision-optimization-level Per-layer Precision Optimization Level (POL) is a powerful feature that allows for fine-grained control over the precision level of individual operations within a model. This capability offers significant advantages in terms of improving model convergence stability and addressing numerical issues associated with low-precision data types used in kernels. ## Per-Layer POL vs Per-Model POL **Per-Model POL** This approach sets a single precision level for the entire model using the `CsConfig.precision_opt_level` parameter. This method provides a simple and efficient way to control model precision but lacks the granularity to address specific numerical challenges in individual layers. **Per-Layer POL** This approach allows for individual operations (layers) to be annotated with specific precision levels, including both forward and backward passes. This granularity enables a more precise and targeted approach to optimizing model performance and addressing numerical issues. It is achieved by utilizing the cstorch.pol decorator to annotate specific functions within the model code. The granularity of the POL annotation is determined by the content of the decorated function, allowing for individual operations or blocks of operations to be targeted. Importantly, per-layer POL overrides any per-model POL settings, ensuring that the specific operation precision takes precedence. ## CSTorch API To annotate a layer or set of layers, use the `cstorch.pol` decorator. For example: ```python theme={null} @cstorch.pol(level=0) def fc1(x): out = self.fc1(x) return F.relu(out) out = fc1(x) ``` This example demonstrates utilizing the cstorch.pol decorator to annotate all operations within the fc1 function with a precision level (POL) setting of 0. By default, `cstorch.pol` applies the specified precision level to both the forward pass operations as well as their corresponding gradients computation operations during backpropagation. However, the decorator accepts parameters to allow configuring precision policies independently for forward versus backward passes. For example: ```python theme={null} @cstorch.pol(bwd_level=0) # annotates only bwd pass ops. def fc1(x): return self.fc1(x) ``` An alternative way of using the decorator is to pass a layer as a parameter instead of wrapping a function. For example, the example above is equivalent to: ```python theme={null} cstorch.pol(bwd_level=0)( # set POL parameters self.fc1 # pass a layer (callable) )(hidden_states) # pass layer input arguments ``` To implement per-operation precision level (POL) annotations, the cstorch.pol API communicates with the Cerebras PyTorch backend. Specifically, it tags IR nodes in the Layerwise Tensor Compiler (LTC) intermediate representation with precision level attributes. These attributes are then propagated through the subsequent compilation stages on the Cerebras accelerator backend. > [!NOTE] > > Current implementation of per-layer POL only supports annotating MatMul operations. While future updates may expand support to additional operations, this limitation is currently in place. # Profiling the Executor Source: https://training-docs.cerebras.ai/rel-2.5.0/cs-torch/writing-a-custom-training-loop/profiling-the-executor We provide tools through the `DataExecutor` to profile its performance during the run. Currently, the supported activities can be profiled as follows: | Activity | Description | | - | - | | `total_samples` | Total number of samples processed so far | | `total_time` | Elapsed time so far, in seconds | | `rate` | Client side smoothed samples/second of all the samples added since last queried | | `global_rate` | Non-smoothed samples/second since the beginning of when the executor context was entered. For a more detailed explanation see [Measure throughput of your model](../../fundamentals/measure-throughput-of-your-model) | | `samples_per_sec` | Non-smoothed samples/second since the beginning of when the executor context was entered. This value is the same as `global_rate` | | `flops_utilization` | Real flops utilization for the run | You can track activity performance using names and the [`DataExecutor`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.utils.data.DataExecutor "cerebras.pytorch.utils.data.DataExecutor") profiler. For example: ```python theme={null} executor = cstorch.utils.data.DataExecutor(...) ... print(f"Total samples: {executor.profiler.rate_tracker.total_samples}") print(f"Total time: {executor.profiler.rate_tracker.total_time}") print(f"Rate: {executor.profiler.rate_tracker.rate}") print(f"Global rate: {executor.profiler.rate_tracker.global_rate}") print(f"Samples/sec: {executor.profiler.rate_tracker.samples_per_sec}") print(f"Flops utilization: {executor.profiler.rate_tracker.flops_utilization}") ``` # Restartable Dataloaders Source: https://training-docs.cerebras.ai/rel-2.5.0/cs-torch/writing-a-custom-training-loop/restartable-dataloaders In the Cerebras PyTorch API 2.0, we provide revamped support for deterministically restarting any custom input-generating dataloaders used for a run. This feature enables the saving and loading of the dataloader state and seamlessly integrates with our existing mechanism of capturing checkpoints for a run. ## Saving DataLoader State Similar to how you call state\_dict on components such as the model and optimizer to fetch and save state information in our Cerebras H5-based checkpoint format. You can save the state of your dataloader by calling [`state_dict`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.utils.data.DataLoader.state_dict "cerebras.pytorch.utils.data.DataLoader.state_dict") on the Cerebras PyTorch dataloader wrapper that must be initialized at the beginning of a custom training loop. ```python theme={null} cerebras_dataloader = cstorch.utils.data.DataLoader(input_fn, *args, **kwargs) ... state_dict = { "model": model.state_dict(), "optimizer": optimizer.state_dict(), "dataloader": cerebras_dataloader.state_dict(), ... } cstorch.save(state_dict, "") ``` > [!NOTE] > > * Our typical workflow in Model Zoo already includes this call on the Cerebras PyTorch dataloader wrapper to save the state of the dataloader being used for the run. > > * The dataloader state can only be saved at a checkpoint step – i.e. you should wrap the method invoking the call to save the dataloader state in the `checkpoint_closure` decorator. ## Loading DataLoader State Upon restarting a run from a Cerebras checkpoint file, you can fetch the saved dataloader state (if it exists) from the loaded checkpoint and pass it to the [`load_state_dict`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.utils.data.DataLoader.load_state_dict "cerebras.pytorch.utils.data.DataLoader.load_state_dict") method on the Cerebras PyTorch dataloader wrapper to load your dataloader’s state, e.g. ```python theme={null} state_dict = cstorch.load("") model.load_state_dict(state_dict["model"]) optimizer.load_state_dictt(state_dict["optimizer"]) if "dataloader" in state_dict: cerebras_dataloader.load_state_dict(state_dict["dataloader"]) ``` And that is all! Now to specify what “state” information of your dataloader is to be saved in a checkpoint when state\_dict is called on the Cerebras PyTorch dataloader, and how this state information should be loaded to rewind your dataloader, your dataloader must conform to the protocol class [`RestartableDataLoader`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.utils.data.RestartableDataLoader "cerebras.pytorch.utils.data.RestartableDataLoader"). ## Restartable DataLoader API By implementing methods [`state_dict`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.utils.data.RestartableDataLoader.state_dict "cerebras.pytorch.utils.data.RestartableDataLoader.state_dict"), [`aggregate_state_dict`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.utils.data.RestartableDataLoader.aggregate_state_dict "cerebras.pytorch.utils.data.RestartableDataLoader.aggregate_state_dict"), [`deaggregate_state_dict`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.utils.data.RestartableDataLoader.deaggregate_state_dict "cerebras.pytorch.utils.data.RestartableDataLoader.deaggregate_state_dict") and [`load_state_dict`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.utils.data.RestartableDataLoader.load_state_dict "cerebras.pytorch.utils.data.RestartableDataLoader.load_state_dict"), with the appropriate method signatures, your dataloader is guaranteed to be restartable. That is, you are able to save the state of your dataloader in a checkpoint and load it by the mechanism described above. Recall that in a distributed setting, each input worker per CSX creates its own instance of the dataloader for parallelism. Thus, implementing these four methods will determine how your dataloader’s state should be saved and loaded to enable deterministic restarts for such settings. To illustrate the usage of this protocol with an example, we define our CustomRestartableDataLoader class below. The following subsections describe each method signature more generally and within the context of our custom class. ```python theme={null} import cerebras.pytorch as cstorch import torch class CustomRestartableDataLoader(torch.utils.data.DataLoader): def state_dict(self) -> Dict[str, Any]: worker_state = cstorch.distributed.get_worker_state() state_dict = { "worker_step": worker_state.worker_step, "worker_id": worker_state.global_worker_id "some_state_info": ... } return state_dict def aggregate_state_dict(self, worker_states): return { "step_worker_0": worker_states[0]["worker_step"], "id_worker_1": worker_states[1]["worker_id"], "combined_step_sum": worker_states[0]["worker_step"] + worker_states[1]["worker_step"] } def deaggregate_state_dict(self, aggregated_state_dict): if "combined_step_sum" not in aggregated_state_dict: raise RuntimeError( "The aggregated state dict must contain key `combined_step_sum`. " "This means that the dataloader state in the checkpoint you are " "loading from is not compatible with the dataloader currently " "in use." ) return { "combined_step": aggregated_state_dict["combined_step_sum"] } def load_state_dict(self, state_dict): if "combined_step" not in state_dict: raise RuntimeError( "The state dict must contain key `combined_step`, but it does not. " "This means that the dataloader state in the checkpoint you are " "loading from is not compatible with the dataloader currently " "in use." ) print(f"Loading state using combined steps: {state_dict["combined_step"]}") ... ``` ### state\_dict Use this method to specify what state information each input-generating worker should capture at an appliance checkpoint step. By default, each worker captures some internal state info using our new Cerebras dataloader checkpoint format defined by the [`DataLoaderCheckpoint`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.utils.data.DataLoaderCheckpoint "cerebras.pytorch.utils.data.DataLoaderCheckpoint") dataclass. Please refer to the linked docs on this class for detailed information on each attribute. Essentially, in your definition of state\_dict you may choose to save any of the aforementioned internal state info per worker. We expose an API method [`get_worker_state`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.distributed.get_worker_state "cerebras.pytorch.distributed.get_worker_state") that you may utilize in your implementation of state\_dict to fetch the worker’s internal state info, e.g. ```python theme={null} def state_dict(self) -> Dict[str, Any]: worker_state = cstorch.distributed.get_worker_state() state_dict = { "worker_step": worker_state.worker_step, "worker_id": worker_state.global_worker_id "some_state_info": ... } return state_dict ``` > [!NOTE] > > * The call to [`get_worker_state`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.distributed.get_worker_state "cerebras.pytorch.distributed.get_worker_state") is well-defined only inside of your implementation of state\_dict; calling this method anywhere else will result in a RunimeError exception. > > * Ensure that any other state info you choose to save must be picklable using the dill package. ### aggregate\_state\_dict This method accepts the list of individual worker states dicts as an argument. Each state dict inside this list holds per-worker state information as defined in your implementation of the state\_dict signature method. Use this method to specify how to combine the state information of all workers in a single, consolidated state dict, e.g. ```python theme={null} def aggregate_state_dict(self, worker_states): return { "step_worker_0": worker_states[0]["worker_step"], "id_worker_1": worker_states[1]["worker_id"], "combined_step_sum": worker_states[0]["worker_step"] + worker_states[1]["worker_step"] } ``` > [!NOTE] > > * The aggregated state dict represents the state of your dataloader and will eventually be saved in our Cerebras H5 checkpoint file when state\_dict is invoked on the Cerebras PyTorch dataloader wrapper to save your dataloader’s state. > > * In the example above, we’re assuming two total workers used for the run. In the aggregated state dict, we are choosing to save worker 0’s step, worker 1’s global worker id, and the summed step count of both workers as the state of our dataloader. > > * You can expect the worker\_states list to be ordered by the global worker id of each worker. ### deaggregate\_state\_dict This method accepts an aggregated state dict as an argument. The aggregated state dict represents the state of your dataloader, as specified in the aggregate\_state\_dict method signature of your dataloader. To load your data loader’s state, use this method to specify how the consolidated dataloader state loaded from a checkpoint should be disaggregated into a single state dict defining how each worker should load its state, e.g. ```python theme={null} def deaggregate_state_dict(self, aggregated_state_dict): if "combined_step_sum" not in aggregated_state_dict: raise RuntimeError( "The aggregated state dict must contain key `combined_step_sum`. " "This means that the dataloader state in the checkpoint you are " "loading from is not compatible with the dataloader currently " "in use." ) return { "combined_step": aggregated_state_dict["combined_step_sum"] } ``` In the example above, our implementation has an explicit check to ensure that we’re loading state captured by this dataloader. Upon restart, we assume that each worker cares about the combined step count of all workers in the previous run at the checkpoint we’re loading from; thus, the deaggregation method constructs and returns a single state holding the combined step info. > [!NOTE] > > This method will be particularly useful when the number of workers per box changes between subsequent runs; use this to specify which state dict should be loaded by each worker upon restart. ### load\_state\_dict This method accepts a disaggregated state dict as an argument, as defined in your implementation of deaggregate\_state\_dict. Use this method to specify how the worker should load its state from the provided, disaggregated state dict, e.g. ```python theme={null} def load_state_dict(self, state_dict): if "combined_step" not in state_dict: raise RuntimeError( "The state dict must contain key `combined_step`, but it does not. " "This means that the dataloader state in the checkpoint you are " "loading from is not compatible with the dataloader currently " "in use." ) print(f"Loading state using combined steps: {state_dict["combined_step"]}") ... ``` Again, we have an explicit check to ensure that the disaggregated state dict being used by each worker to load its state upon restart is the same as that specified by our data loader’s implementation of deaggregate\_state\_dict. For this example, each worker simply prints the combined step count from the previous run, but you can imagine using this step count to set other properties on your data loader that enable it to restart deterministically. ### Putting it All Together Combining all of the above steps, we have the following steps to set up our custom restartable dataloader whose state can be captured via checkpointing: ```python theme={null} def restartable_torch_dataloader(batch_size): from torchvision import datasets train_dataset = datasets.MNIST( "/path/to/data", train=True, download=True, transform=transforms.Compose( [ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)), transforms.Lambda( lambda x: torch.as_tensor(x, dtype=torch.float16) ), ] ), target_transform=transforms.Lambda( lambda x: torch.as_tensor(x, dtype=torch.int32) ) ) return CustomRestartableDataLoader(train_dataset, batch_size=batch_size, shuffle=True) cerebras_dataloader = cstorch.utils.data.DataLoader(restartable_torch_dataloader, batch_size=64) ... @cstorch.checkpoint_closure def save_checkpoint(): state_dict = { "model": model.state_dict(), "optimizer": optimizer.state_dict(), "dataloader": cerebras_dataloader.state_dict(), ... } cstorch.save(state_dict, "") ... def load_checkpoint(checkpoint_file_path): state_dict = cstorch.load(checkpoint_file_path) model.load_state_dict(state_dict["model"]) optimizer.load_state_dictt(state_dict["optimizer"]) if "dataloader" in state_dict: cerebras_dataloader.load_state_dict(state_dict["dataloader"]) ``` > [!NOTE] > > It is not necessary for your dataloader to be of type torch.utils.data.DataLoader to enable the saving and loading of its state; in fact, any iterable that returns a structure comprising torch tensors can be programmed to be restartable as long as it implements the four signature methods conforming to the Cerebras [`RestartableDataLoader`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.utils.data.RestartableDataLoader "cerebras.pytorch.utils.data.RestartableDataLoader") protocol class. # Saving Loading Checkpoint Source: https://training-docs.cerebras.ai/rel-2.5.0/cs-torch/writing-a-custom-training-loop/saving-loading-checkpoints To save and load weights in a Cerebras run, we provide a custom Cerebras H5 based checkpoint format that is far more performant and efficient compared to the core PyTorch Pickle-based checkpoint format, especially when it comes to any models with extremely large weights, such as Large Language Models (LLMs). To save a checkpoint, we provide a [`cerebras.pytorch.save`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.save) function that you can use in exactly the same way as `torch.save`: ```python theme={null} state_dict = { "model": model.state_dict(), "optimizer": optimizer.state_dict(), ... } cstorch.save(state_dict, "") ``` Similarly, we provide a [`cerebras.pytorch.load`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.load) function that can also be used in exactly the same way as `torch.load`: ```python theme={null} state_dict = cstorch.load("") model.load_state_dict(state_dict["model"]) optimizer.load_state_dictt(state_dict["optimizer"]) ... ``` ### Checkpoint Closures It is only possible to fetch weights on predetermined checkpoint steps configured using the [`DataExecutor`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.utils.data.DataExecutor). The reason this is so, is to make training more performant. For example, if the configuration was `checkpoint_steps=100`, you are only allowed to fetch the weights to take a checkpoint every 100th step and at the very end on the last step. To aid this, you can use the [`checkpoint_closure`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.checkpoint_closure) decorator which is a [step closure](../../cs-torch/writing-a-custom-training-loop/step-closures) that checks that the current step is a checkpoint step before calling the function. In addition, using this decorator ensures that the weights are available to fetch from the server before they can be saved to the checkpoint file. ```python theme={null} @cstorch.checkpoint_closure def save_checkpoint(): state_dict = { "model": model.state_dict(), "optimizer": optimizer.state_dict(), ... } cstorch.save(state_dict, "") ``` ### Converting Checkpoints to a Pickle-Based Format If you have a checkpoint in the Cerebras H5-based format and wish to use it in a CPU/GPU workflow, it can easily be converted to a PyTorch pickle-based format: ```python theme={null} state_dict = cstorch.load("", map_location="cpu") torch.save(state_dict, "") ``` > [!NOTE] > > This will eagerly load the entirety of the checkpoint into memory. Thus, it may cause memory issues when loading checkpoints for very large models. > > In most cases, converting the checkpoint is unnecessary as the lazily loaded checkpoint acquired via the [`cerebras.pytorch.load`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.load) function will also work in CPU/GPU workflows. # Sparsifying Models Source: https://training-docs.cerebras.ai/rel-2.5.0/cs-torch/writing-a-custom-training-loop/sparsifying-models Learn strategies for integrating sparsity into Cerebras models to optimize performance and computational efficiency across neural network architectures. Sparse models require fewer FLOPs per step and less memory to store, making them compelling architectures for deep learning research and application. Sparse training algorithms set portions of model weights to zero and often adjust these proportions throughout training. The Cerebras PyTorch API enables practitioners to easily implement and extend sparsity algorithms and schedules, and directly train with sparse weights on the Cerebras system. This process, which involves setting a proportion of the model’s weights to zero, not only streamlines the model by focusing on essential features but also aids in regularization, potentially improving generalization to new data. Various strategies exist to implement sparsity, each suitable for different models and tasks, making sparsity a versatile tool in optimizing machine learning models for performance and efficiency. The Cerebras PyTorch API enables practitioners to train with sparse weights, leading to a significant reduction in FLOPs per step. ## How to Sparsify Your Model Sparsifying a model is straightforward with the cstorch API. Here’s an example where 30% of the values in every parameter (such as weights, biases, embeddings, among others) are set to zero prior to training: ```python theme={null} import cerebras.pytorch as cstorch # Initialize your backend backend = cstorch.backend(...) # Define your model within the backend's device context with backend.device: model: torch.nn.Module = ... # Compile the model with the backend compiled_model = cstorch.compile(model, backend) # Initialize a sparsity algorithm with 30% sparsity sparsity = cstorch.sparse.Static(sparsity=0.3) # Apply the sparsity algorithm to the model model.apply(sparsity) ``` After the call to `model.apply(sparsity)`, your model parameters are sparsified, enhancing training efficiency. ### Important considerations 1. Only once the model has been compiled, apply sparsity with [`cstorch.compile`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.compile), ensuring all parameters are on the Cerebras device. 2. To exclude certain parameters from sparsity, set `param.requires_dense = True`. If a parameter does not have this attribute, the algorithm assumes that it is `False`. ### Sparsifying Optimizers For training, simply sparsifying the model’s parameters is insufficient; the optimizer must be sparsified as well. To extend sparsity to your optimizer: ```python theme={null} optimizer.apply(sparsity) ``` When you sparsify an optimizer, you’re not only adjusting the optimizer’s state but also setting up mechanisms such as installing various hooks to ensure that sparsity patterns are maintained and updated appropriately during training, specifically when `optimizer.step()` is executed. Executing `optimizer.apply(sparsity)` transforms your optimizer into a sparse optimizer. ### Important considerations 1. The sparsity algorithm targets all optimizer states associated with a parameter, assuming the state tensor matches the parameter’s shape. To exempt certain state tensors from sparsification, designate them as requiring to be dense: ```python theme={null} optmizer.state[p][name].requires_dense = True ``` If a state tensor does not have this attribute, the algorithm assumes that it is `False`. 1. Sparsity algorithms typically include a hook that updates the sparsity pattern after each `optimizer.step()` call. This automatic update feature can be deactivated if necessary: ```python theme={null} sparsity.autoupdate = False ``` ## Sparsity Algorithms The cstorch API offers several out-of-the-box sparsity algorithms, including: * [`Static`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.Static) * [`GMP`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.GMP) * [`SET`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.SET) * [`RigL`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.RigL) ## Composing Sparsity Algorithms You can apply distinct sparsity strategies to various parameter groups within your model. For instance, one group of weights might be statically reduced to 30% of its original values, while another group undergoes dynamic sparsity adjustments using the SET algorithm. This can be achieved by composing different sparsity algorithms into a composable strategy with the [`Group`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.Group) class. ```python theme={null} class Model(torch.nn.Module): def __init__(self): super().__init__() self.fc1 = torch.nn.Linear(25, 20) self.fc2 = torch.nn.Linear(20, 10) ... sparsity = cstorch.sparse.Group({ "fc1.*": cstorch.sparse.Static(sparsity=0.3) "fc2.*": cstorch.sparse.SET( sparsity=0.9, update={"freq": 1000}, drop_fraction=0.3 ) }) model.apply(sparsity) ``` This grouped sparsity algorithm applies static sparsity to all model parameters corresponding to the `fc1.*` glob pattern, while employing the SET sparsity algorithm for parameters that match the `fc2.*` glob pattern. ## Writing Custom Sparsity Algorithms All sparsity algorithms must inherit from the base [`SparsityAlgorithm`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.SparsityAlgorithm). ```python theme={null} class CustomSparsity(cstorch.sparse.SparsityAlgorithm): def __init__(self, ..., **kwargs): ... super().__init__(**kwargs) ... def update(self): ... for sparse_param in self.sparse_params.values(): p = sparse_param.data mask = sparse_param.mask ... sparse_params.mask = new_mask ... ``` The only abstract method that must be overriden is [`update`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.SparsityAlgorithm.update) which takes care of updating the sparsity patterns for all sparse parameters. For algorithms that dynamically change the sparsity pattern, there is a convenient [`DynamicSparsityAlgorithm`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.DynamicSparsityAlgorithm) class that you can inherit from that takes care of many of the implementation details required to facilitate dynamic sparsity. ```python theme={null} class CustomDynamicSparsity(cstorch.sparse.DynamicSparsityAlgorithm): def __init__(self, ..., **kwargs): ... super().__init__(**kwargs) ... def update_mask(p, mask, sparsity) -> torch.Tensor: ... ``` [`DynamicSparsityAlgorithm`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.DynamicSparsityAlgorithm) already implements `update`, but it exposes a new abstract method `update_mask` that must be overriden instead. `update_mask` takes in the existing sparsity pattern in the form of a mask tensor and must return the new sparsity pattern in the form of a mask tensor as well. See [`GMP`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.GMP), [`SET`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.SET), and [`RigL`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.RigL) for examples of how to implement [`update_mask`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.DynamicSparsityAlgorithm.update_mask). In addition, there are many building blocks that are provided that can be used directly, inherited from, or composed to help build new [`DynamicSparsityAlgorithm`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.DynamicSparsityAlgorithm) subclasses. See [Customizing Sparsity & Reference](../../cs-torch/cerebras-pytorch-api/cerebras-pytorch-sparse#customizing-sparsity-and-reference) for more details. Once you’ve written your custom sparsity algorithm, as long as it’s available in the global scope, you can use it directly or even through a call to [`configure`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.configure) by setting the `algorithm` to be the name of your custom sparsity algorithm class. By extension, this means that you can use it in ModelZoo in a similar way by setting the `algorithm` to be the name of your custom sparsity algorithm class in your params YAML file. ## Implementation Notes The Cerebras Wafer-Scale Cluster natively implements sparse computations in the Compressed Sparse Row (CSR) format. For user convenience, sparse models are represented as a combination of dense tensors and masks at the PyTorch level, with the compiler seamlessly converting between these representations. While PyTorch provides tools for [representing sparse tensors](https://pytorch.org/docs/stable/sparse.html) and [utilities for pruning networks](https://pytorch.org/tutorials/intermediate/pruning_tutorial.html), these features might not fully align with the needs of the Cerebras Wafer Scale Engine (WSE). Sparse tensors in PyTorch require specialized kernels and may not be entirely compatible with existing models and utilities. Notably, a `torch.nn.Parameter` cannot directly accommodate a `torch.sparse.Tensor` without specific adjustments. The `torch.prune` utilities are convenient, but the asynchronous and precompiled nature of computation on the WSE requires a custom solution. Similar to how `torch.prune` handles its mask tensors, when the sparsity algorithm is applied to the model, every parameter that is sparsified has a mask tensor registered as a stateful buffer next to it in the module that owns the parameter. For example, take the following simple model: ```python theme={null} model = torch.nn.Linear(2, 2, bias=False) ``` Initially, the model’s state dictionary appears as follows: ```python theme={null} { "weight": torch.Tensor(...) } ``` After applying sparsity, the state dictionary is augmented to include mask tensors, illustrating the model’s transition to a sparsified state: ```python theme={null} { "weight": torch.Tensor(...) "weight_mask": torch.Tensor(...) } ``` Here, the `weight` and `weight_mask` tensors collectively represent the sparsified `weight`, showing how sparsity is represented within the model’s architecture. # Step Closures Source: https://training-docs.cerebras.ai/rel-2.5.0/cs-torch/writing-a-custom-training-loop/step-closures By design, in the execution schema used by the Cerebras Wafer-Scale cluster, the client and the server run asynchronously to each other. This was to prevent the server from becoming bottlenecked by any client processes such as disk I/O or networking. However, this means that a computed tensor may not be available to fetch from the server when the client requests it. For example, the call to compile happens in the first iteration of the training loop. Until compile is complete and execution starts on the cluster, no tensor is available to fetch. To handle this, we introduce the concept of a step closure via the [`step_closure`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.step_closure "cerebras.pytorch.step_closure") decorator, e.g. ```python theme={null} @cstorch.step_closure def closure(loss): print(f"Loss: {loss}") ``` Tensors that are passed into a “step closure” are fetched from the server and their value is materialized before the closure is actually called. If the tensor is not yet available; it waits until the server “catches up” with the current step, and the tensor value is available to be fetched before actually calling the closure. ### Example Usage You can call step closures either inside the traced step function or outside of it: ```python theme={null} @cstorch.step_closure def check_nan(loss): assert not torch.isnan(loss).any() @cstorch.step_closure def print_loss(loss): print(f"Loss: {loss}") @cstorch.trace def training_step(inputs, targets): outputs = compiled_model(inputs) loss = loss_fn(outputs, targets) check_nan(loss) loss.backward() optimizer.step() optimizer.zero_grad() return loss for inputs, targets in executor: loss = training_step(inputs, targets) print_loss(loss) ``` # Writing Custom Optimizers Source: https://training-docs.cerebras.ai/rel-2.5.0/cs-torch/writing-a-custom-training-loop/writing-custom-optimizers Learn how to write a Cerebras-compliant custom optimizer. Start by creating a subclass of [`cerebras.pytorch.optim.Optimizer`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.Optimizer "cerebras.pytorch.optim.Optimizer"). For example: ```python theme={null} class CustomOptimizer(cstorch.optim.Optimizer): def __init__(self, params, ...): ... defaults = ... super().__init__(params, defaults, enable_global_step=...) ... def preinitialize(self): ... def step(self, closure=None): ... def state_names_to_sparsify(self): ... ``` As seen in the above example, similar to `torch.optim.Optimizer`, the base [`Optimizer`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.Optimizer "cerebras.pytorch.optim.Optimizer") class expects three arguments: the model parameters, the param group defaults, and the optional `enable_global_step` that will define a global step state variable for each parameter. In addition, there are two abstract methods that must be overridden: * [`preinitialize`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.Optimizer.preinitialize "cerebras.pytorch.optim.Optimizer.preinitialize") This method is used to initialize any state variables that will be used by the optimizer. For example, [`SGD`](../../cs-torch/cerebras-pytorch-api/cerebras-pytorch-optim#class-cerebras-pytorch-optim-sgd-params-lr-momentum-0-dampening-0-weight-decay-0-nesterov-false-maximize-false "cerebras.pytorch.optim.SGD") defines its momentum buffers in its `preinitialize` method. > [!NOTE] > > To remain Cerebras-compliant, no optimizer state variables may be initialized outside of the `preinitialize` method. For optimal performance, when initializing the state tensors that are filled with some constant value, use the [creation ops](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#creation-ops) that are available in the `cstorch` package to lazily initialize them. These ops will lazily initialize and fill the tensor, meaning that they take up very little memory and can be initialized much quicker than their `torch` counterparts when running on the cluster. Please see the source code for the optimizers in [cerebras.pytorch](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html) for examples. * [`step`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.Optimizer.step "cerebras.pytorch.optim.Optimizer.step") This method is where the optimizer step is implemented. Note that due to the nature of lazy tensor tracing and execution, there may not be any Python level conditions or loops used to dynamically define the control flow. This means that only torch ops (such as `torch.where`) may be used.However, static structures are allowed. For example, a loop with a fixed number of iterations, or a Python conditional that doesn’t involve any torch tensors whose conditional involves only constant variables. Once you’ve written your custom optimizer, as long as its available in the global scope, you can use it in ModelZoo in a similar way by setting the `optimizer_type` to be the name of your custom optimizer class in your params YAML file. # Define Environment Variables For Input Workers Source: https://training-docs.cerebras.ai/rel-2.5.0/fundamentals/define-environment-variables-for-input-workers In a Wafer-Scale Cluster execution, the input pipeline runs on input worker nodes within the cluster, which are separate processes started by the Appliance on different CPU nodes. ## Overview As such, any environment variables set on the user process are not seen by the input workers as they run on different nodes. But since input workers run user code (e.g., dataloader), it is desirable in some cases to have some environment variables set on user side to be visible by workers as well. This section describes how to set environment variables on the user node that are visible by the input workers that stream data to the system. ## Procedure For this, we provide a drop-in replacement for `os.environ` with an identical interface. This object can be imported as follows: ```Bash theme={null} >>>from cerebras.appliance.environment import appliance_environ ``` The main difference of this object compared to `os.environ` is that it tracks any environment variables **set** through it and sends them to the input workers. Setting an environment variable through `appliance_environ` effectively stores the key and when an execute job is created, values of these environment variables are read and sent to the input workers. The input workers then see these variables as if they were set through `os.environ`. ## Important considerations * This object **does not** track environment variables that are **not** set through it. For example, if you set an environment variable through os.environ, while this object will see the value, it will not transfer this variable to the input workers. * These environment variables are sent to the Appliance when an execute job is requested. Setting variables after an execute job is created has no effect until the next execute job is created (if any). * Environment variables set throug appliance\_environ are injected into the input workers **after** the worker process has been created. This means setting environment variables that need to exist before the Python interpreter is started will not work. For example, setting PYTHONPATH will not have the intended effect. This object is mainly for user-level environment variables set within a run. ## Usage Here’s an example of how to use this object: ```Bash theme={null} >>> # Let's start with a clean environment >>> assert "foo" not in os.environ and "bar" not in app.environ >>> # Import the appliance_environ object >>> from cerebras.appliance.environment import appliance_environ >>> # Now let's set env variable "foo" through appliance_environ. >>> # When the input workers are created, they will see this updated >>> # value. >>> appliance_environ["foo"] = "1" >>> assert appliance_environ["foo"] == "1" # appliance_environ sees the updated value >>> assert os.environ["foo"] == "1" # os.environ also sees the updated value >>> # Now let's set env variable "bar" through os.environ. >>> # Since "bar" is set through "os.environ", when the input workers are >>> # created, they won't have access to this key. >>> os.environ["bar"] = "2" >>> assert appliance_environ["bar"] == "2" # appliance_environ sees the updated value ``` ## Conclusion The introduction of the specialized environment variable manager, `appliance_environ`, provides a robust solution for propagating environment variables from the user node to input worker nodes in a Wafer-Scale Cluster setup. This functionality is essential for ensuring that user code running on input workers can access necessary environment variables, despite the inherent separation of these processes across different CPU nodes. By utilizing appliance\_environ to set environment variables, users can ensure that their settings are consistently applied across all nodes involved in the execution, thereby maintaining the desired environment for data streaming and processing. This approach not only simplifies the configuration process but also enhances the reliability and efficiency of the input pipeline in distributed computing environments. # Import User Dependencies In Cerebras Source: https://training-docs.cerebras.ai/rel-2.5.0/fundamentals/import-user-dependencies-in-cerebras If you are developing your own data loader, you might need to provide specific dependency packages in the virtual Python environments to support your data loader functions. The `Custom Worker Container Workflow` provides seamless support for importing user-specific dependency packages in the Python environments into Cerebras appliance. With this feature, you do not need any special handling. In the event where the custom worker container failed to be created, a fallback policy will take into effect by mounting the site packages from the user node Python virtual environment to the worker environment via a predefined NFS-based cluster volume. Both the custom worker container feature and the venv mounting fallback policy have been enabled by default. If you would like to disable the features, there are two Cerebras-specific options that can support that. We call these options `debug_args`. * To disable the custom worker container feature, the option is named `debug_args.debug_usr.skip_image_build`. Setting this option to True will disable this feature. * To disable the venv mounting fallback policy, the option is named `debug_args.debug_usr.skip_user_venv_mount`. Setting this option to True will disable the fallback policy. ## Procedure To disable custom worker container workflow, follow the steps below: 1. Save the following script as `debug_args_writer.py` on any accessible directory on the user node: ```Bash theme={null} from cerebras.appliance.run_utils import write_debug_args from cerebras.appliance.pb.workflow.appliance.common.common_config_pb2 import DebugArgs debug_args = DebugArgs() debug_args.debug_usr.skip_image_build = True debug_args.debug_usr.skip_user_venv_mount = True out_file = "debug_args.out" write_debug_args(debug_args, out_file) ``` 2. Run it inside a Cerebras virtual environment you have setup on the user node, see [Setup and installation](../getting-started/setup-and-installation.mdx): ```Bash theme={null} (venv_cerebras_pt) $ python debug_args_writer.py ``` This script will produce a file debug\_args.out. You can then add the additional option when invoking `run.py` as follows: ```Bash theme={null} (venv_cerebras_pt) $ cszoo fit --debug_args_path debug_args.out ``` > [!NOTE] > > Currently, the custom worker container workflow only accounts for Python dependencies that were pip installed on the user node and assumes Internet and PyPI access from the workers in Cerebras appliance. If workers do not have access to the Internet or PyPI, the workflow will fail and the fallback policy will take into effect. # Configure Notifications Source: https://training-docs.cerebras.ai/rel-2.5.0/fundamentals/job-notifications Learn how to configure email, Slack, or PagerDuty notifications for your jobs. In your Trainer configuration (YAML) file, you can configure notifications for training and fine-tuning jobs under the [`backend`](../../rel-2.5.0/model-zoo/trainer-configuration-overview#backend) key. Modify your Trainer configuration file to include the `notifications` parameter. Use the tabs to see examples for each option: ```yaml email theme={null} trainer: init: model_dir: /model backend: backend_type: CSX cluster_config: num_csx: 1 notifications: - mailto: - "my_email_address@cerebras.com" ``` ```yaml Slack theme={null} trainer: init: model_dir: /model backend: backend_type: CSX cluster_config: num_csx: 1 notifications: - slack: - "" ``` ```yaml PagerDuty theme={null} trainer: init: model_dir: /model backend: backend_type: CSX cluster_config: num_csx: 1 notifications: - pagerduty: - "" ``` > [!NOTE] > > This notification system is specific to training and fine-tuning workflows and is not compatible with data preprocessing jobs. Currently, these notifications will only forward error messages. # Kernel Autogeneration with Autogen Source: https://training-docs.cerebras.ai/rel-2.5.0/fundamentals/kernel-autogeneration-with-autogen To optimize model performance on Cerebras hardware, we use a mix of pre-written and AutoGen (automatically generated) kernels. While the core library of handwritten kernels addresses many standard operations, AutoGen kernels step in under certain conditions: * Missing Operations: If a model needs an operation that’s not in the handwritten library, AutoGen kernels are generated to support these operations. * Performance Optimization: AutoGen can create specialized, fused kernels for operations, even for those operations that already have existing handwritten implementations. This is especially useful for complex operations, such as loss functions, where AutoGen kernels can offer superior performance. The Cerebras compiler automatically generates these custom kernels to enhance your model’s efficiency. ## Autogenerating fused kernels for loss operations AutoGen supports numerous PyTorch loss functions by creating fused kernels that replace or outperform handwritten versions. To use AutoGen for a PyTorch loss: **1.** Import the PyTorch loss from the Model Zoo **2.** Set `use_autogen=True`. The default value of `use_autogen` is True. ```Bash theme={null} from cerebras_pytorch/src/cerebras/pytorch/nn/modules import BCELoss loss = BCELoss(reduction='mean', use_autogen=True) ``` ## List of supported losses * BCELoss * CrossEntropyLoss * Loss.BCEWithLogitsLoss * Loss.GaussianNLLLoss * Loss.HingeEmbeddingLoss * Loss.HuberLoss * Loss.KLDivLoss * Loss.L1Loss * Loss.MarginRankingLoss * Loss.MSELoss * Loss.MultiLabelSoftMarginLoss * Loss.MultiMarginLoss * Loss.NLLLoss * Loss.PoissonNLLLoss * Loss.SmoothL1Loss * Loss.TripletMarginLoss * Loss.TripletMarginWithDistanceLoss Unsupported losses: * Loss.CosineEmbeddingLoss (Will compile to handwritten kernels) * Mish ## Unsupported losses All unsupported losses will still compile using a custom-written kernel. * Loss.CosineEmbeddingLoss (Will compile to handwritten kernels) ## Autogenerate kernels for customized losses Creating custom losses may result in compilation failure. If this occurs, enable AutoGen for the custom loss by adding the `@autogen_loss` decorator for the loss class. ```Bash theme={null} from cerebras_pytorch/src/cerebras/pytorch/nn/modules import autogen_loss @autogen_loss class CustomLoss(nn.Module): def __init__(self, ...): ... ``` ## Implementation notes ## Release 2.2.0 In Release 2.2.0, the Autogen feature is temporarily unavailable. ## Release 2.1.1 In Release 2.1.1, the automatic kernel generation feature (autogen) is temporarily unavailable. Make sure that in your runconfig file, you set `autogen_policy:disabled` if you were previously using it. ## Release 1.9.1 In Release 1.9.1, we enabled the following AutoGen capabilities * Support for PyTorch operations (e.g., nonlinearities) * Improving the performance of PyTorch losses through fused kernels * Support for user-defined loss functions For any issues transitioning to a version with mandatory AutoGen, please contact Cerebras Support for guidance. # Launch a Job Source: https://training-docs.cerebras.ai/rel-2.5.0/fundamentals/launch-your-job Learn how to launch a job on a Cerebras cluster. ## Prerequisites Before launching a job: * Complete the instructions in our [setup and installation](../getting-started/setup-and-installation) guide (including activating your virtual environment). * Preprocess your data. For general guidance, see the [Data Preprocessing](../model-zoo/components/data-preprocessing/data-preprocessing) documentation or follow our [Data Preprocessing Quickstart](../model-zoo/core-workflows/quickstart-guide-for-data-preprocessing) guide. ## CLI Arguments and Flags Use the Model Zoo CLI to launch a training, validation, or upstream and downstream validation job: ```Bash Training theme={null} cszoo fit params_model.yaml [additional-args] ``` ```Bash Validation theme={null} cszoo validate params_model.yaml [additional-args] ``` ```Bash Up + Downstream Validation theme={null} cszoo validate_all params_model.yaml [additional-args] ``` ### Required Arguments | Flag | Description | | - | - | | `CSX` | Specifies that the target device for execution is a Cerebras Cluster. | | `--params ` | Path to a YAML file containing model/run configuration options. | ### Optional Arguments | Flag | Description | Default | | - | - | - | | `--compile_only` | Compiles the model by matching to Cerebras kernels and mapping to hardware. No execution occurs. Compile artifacts are stored in the specified `--compile_dir`. For training with a pre-compiled model, use the same `--compile_dir`. Cannot be used with `--validate_only`. | `None` | | `--validate_only` | Performs lightweight compilation to validate model compatibility with Cerebras kernels. Does not map to hardware or execute. Cannot be used with `--compile_only`. | `None` | | `--model_dir ` | Directory for storing model checkpoints and TensorBoard events files. | `$CWD/model_dir` | | `--compile_dir ` | Directory for storing compile artifacts in the Cerebras cluster. | `None` | | `--num_csx <1,2,4,8,16>` | Number of CS-X systems to use for training. | `1` | | `--job_priority` | Sets the job priority. Valid inputs are p1, p2, and p3. Learn more about how jobs are prioritized [here](../cluster-monitoring/cerebras-job-scheduling-and-monitoring/job-priority). | `p2` | > [!NOTE] > > `--validate_only` performs a lightweight compilation to check model compatibility with Cerebras kernels, while `cszoo validate` verifies that a model's configuration meets expected requirements. For a more comprehensive list, use the help command: ```Bash theme={null} cszoo fit --h ``` ## Launch a Job **1. Validate the Job (optional)** To verify your model's compatibility, use the `--validate_only` flag. This performs a quick compatibility check without executing a full run: ```Bash theme={null} cszoo fit params_model.yaml \ CSX \ --params params.yaml \ --num_csx=1 \ --validate_only ``` **2. Compile the Model** Generate executable files for your model using the `--compile_only` flag. This step typically takes 15-60 minutes: ```Bash theme={null} cszoo fit params_model.yaml \ CSX \ --params params.yaml \ --num_csx=1 \ --model_dir \ --compile_only ``` > [!TIP] > > Speed up subsequent runs by reusing compiled artifacts. Just use the same --compile\_dir path for both compilation and execution. **3. Execute the Job** To run the job: ```Bash theme={null} cszoo fit params_model.yaml \ CSX \ --params params.yaml \ --num_csx=1 \ --model_dir \ ``` Here is an example of a typical output log for a training job: ```Bash theme={null} Transferring weights to server: 100%|██| 1165/1165 [01:00<00:00, 19.33tensors/s] INFO: Finished sending initial weights INFO: | Train Device=CSX, Step=50, Loss=8.31250, Rate=69.37 samples/sec, GlobalRate=69.37 samples/sec, LoopTimeRemaining=0:13:21, TimeRemaining=0:13:21 INFO: | Train Device=CSX, Step=100, Loss=7.25000, Rate=68.41 samples/sec, GlobalRate=68.56 samples/sec, LoopTimeRemaining=0:11:53, TimeRemaining=0:11:53 INFO: | Train Device=CSX, Step=150, Loss=6.53125, Rate=68.31 samples/sec, GlobalRate=68.46 samples/sec, LoopTimeRemaining=0:10:24, TimeRemaining=0:10:24 INFO: | Train Device=CSX, Step=200, Loss=6.53125, Rate=68.54 samples/sec, GlobalRate=68.51 samples/sec, LoopTimeRemaining=0:08:55, TimeRemaining=0:08:55 INFO: | Train Device=CSX, Step=250, Loss=6.12500, Rate=68.84 samples/sec, GlobalRate=68.62 samples/sec, LoopTimeRemaining=0:07:24, TimeRemaining=0:07:24 INFO: | Train Device=CSX, Step=300, Loss=5.53125, Rate=68.74 samples/sec, GlobalRate=68.63 samples/sec, LoopTimeRemaining=0:06:00, TimeRemaining=0:06:00 INFO: | Train Device=CSX, Step=350, Loss=4.81250, Rate=68.01 samples/sec, GlobalRate=68.47 samples/sec, LoopTimeRemaining=0:04:29, TimeRemaining=0:04:29 INFO: | Train Device=CSX, Step=400, Loss=5.37500, Rate=68.44 samples/sec, GlobalRate=68.50 samples/sec, LoopTimeRemaining=0:02:59, TimeRemaining=0:02:59 INFO: | Train Device=CSX, Step=450, Loss=6.43750, Rate=68.43 samples/sec, GlobalRate=68.49 samples/sec, LoopTimeRemaining=0:01:28, TimeRemaining=0:01:28 INFO: | Train Device=CSX, Step=500, Loss=5.09375, Rate=66.71 samples/sec, GlobalRate=68.19 samples/sec, LoopTimeRemaining=0:00:00, TimeRemaining=0:00:00 INFO: Training completed successfully! INFO: Processed 60500 sample(s) in 887.2672743797302 seconds. ``` > [!NOTE] > > * Validation jobs are run on a single CS-X system. For multi-CS-X training, use the `--num_csx` flag. > > * Monitor jobs using the [csctl tool](../cluster-monitoring/cerebras-job-scheduling-and-monitoring/cli-for-job-monitoring-csctl) or the [Grafana dashboard](../cluster-monitoring/cerebras-job-scheduling-and-monitoring/cluster-monitoring-with-grafana). ### Time Estimation Metrics There are two time estimation metrics to help you track training and eval progress: 1. `LoopTimeRemaining` displays the estimated time remaining in your current operation loop, where a loop is a single training iteration, a single validation dataloader execution, or an eval harness run. 2. `TimeRemaining` shows the estimated total time remaining for your entire run, whether it's a complete training session (`fit`) or a validation run (`validate` or `validate_all`). #### Understanding Time Estimates When your run begins, the system needs to observe all different stages (training, checkpointing, validation, etc.) before it can provide a complete time estimate. During this initial period, you'll see `+ ??` appended to the `TimeRemaining` metric. The initial estimate is optimistic since it doesn't account for stages that haven't been measured yet. Once all stages have been observed at least once, the `+ ??` indicator will disappear, and you'll receive more accurate time estimates. These metrics are displayed consistently across CSX, CPU, and GPU hardware. ## Output Files and Artifacts The `` directory contains all run results and artifacts, including: * Checkpoints for model training progress. * TensorBoard events, which can be viewed using: ```Bash theme={null} tensorboard --logdir --bind_all ``` * Configuration files in `/train` or `/eval`. * Run logs in `/cerebras_logs/latest/run.log` or `/cerebras_logs///run.log`. ## Cancel a Job To cancel a job: ```Bash theme={null} csctl cancel job ``` # Cerebras Cluster Settings Source: https://training-docs.cerebras.ai/rel-2.5.0/fundamentals/launch-your-job/cerebras-cluster-settings ## Credentials path and management address The `credentials_path` and `mgmt_address` parameters are set by default in `/opt/cerebras/config` and typically do not require explicit specification. An example configuration in `/opt/cerebras/config` might look like this: ```Bash theme={null} { "clusters": [ { "name": "system-name", "server": "1.2.3.4:9000", "authority": "cluster-server.system-name.example.com", "certificateAuthority": "/opt/cerebras/certs/tls.crt" } ], "contexts": [ { "cluster": "cluster-name", "name": "system-name" } ], "currentContext": "system-name" } ``` ## Python paths and mount directories When running jobs, it’s crucial to include paths required by dataloaders and any external Python packages, as well as the location of the Cerebras Model Zoo. Consider this directory structure as an example: ```Bash theme={null} /path/to/datasets my_dataset/ /path/to/modelzoo modelzoo /path/to/packages package_x package_y ``` If input workers need to access the “my\_dataset” directory and require Python modules from the Model Zoo, “package\_x”, and “package\_y”, you would specify the command like this: ```Bash theme={null} cszoo fit params.yaml \ --mount_dirs /path/to/datasets /path/to/modelzoo /path/to/packages \ --python_paths /path/to/packages /path/to/modelzoo ``` > [!NOTE] > > If some paths have a common parent folder, you only need to specify the parent in the `--mount_dirs` or `--python_paths arguments`. For instance, if the Model Zoo is at `/cb/home/user/modelzoo` and data is at `/cb/home/user/data`, you only need to specify `--mount_dirs /cb/home`. You can also set defaults for `mount_dirs` and `python_paths` in a YAML file and export it as an environment variable to streamline command line usage: ```Bash theme={null} export CEREBRAS_WAFER_SCALE_CLUSTER_DEFAULTS=/path/to/defaults/file.yaml ``` With this environment variable set, you won’t need to specify `--mount_dirs` and `--python_paths` when running a Cerebras Model Zoo job, unless you’re adding additional paths. # Managing Cluster Access Controls Source: https://training-docs.cerebras.ai/rel-2.5.0/fundamentals/managing-cluster-access-controls In scenarios involving multiple groups and users on a Cerebras Wafer-Scale cluster within your organization, certain specific requirements may arise: ## Overview * Ensuring that “User A” is unable to access or execute training jobs using the credentials of “User B”. * Providing “User C”, who is a member of multiple groups within a larger organization, with access to all relevant groups at the appropriate privilege level. All of this is handled by the Wafer Scale Cluster, with no specific action required by the user. ## Procedure When a job is submitted from the user node, it is accompanied by a token that contains the user’s unique user ID (`uid`) or group ID (`gid`). This `uid` or `gid`, which identifies the job’s submitter on the Wafer-Scale cluster, configures the SecurityContext within a Kubernetes pod responsible for managing the appliance and granting access to NFS-mounted storage. The `root` user on the user nodes maintains a file containing a secret key. This key is also stored within the `User-Auth Library` in the Wafer-Scale cluster. Access to this secret file is limited to the `root` user, preventing other users from reading or writing to it. A binary file, owned by the `root` user and inaccessible to non-privileged users, is invoked. When called by non-privileged users, this binary file invokes the system calls to retrieve `uid`, `gid`, or `groups` information for the invoking user, uses the secret key to encrypt the user’s information, and generates an authentication token with a predefined time-to-live. Subsequently, this authentication token is embedded in the job request to be submitted to the cluster management server. The cluster management server performs validation of the authentication token, extracting relevant user and group details and then launches the job only if the token is verified as valid. ## Conclusion The user authentication mechanism on a Cerebras Wafer-Scale cluster is designed to ensure secure and isolated access for multiple users and groups within an organization. By leveraging a robust system that integrates unique user and group IDs with encrypted tokens, the cluster maintains strict access controls, ensuring that users can only execute and access their own jobs and data. This system, operating transparently to the user, ensures a high level of security without compromising ease of use, effectively addressing key organizational requirements for confidentiality and data integrity in a multi-user environment. # Measure Model Throughput Source: https://training-docs.cerebras.ai/rel-2.5.0/fundamentals/measure-throughput-of-your-model Learn how to measure the training throughput of your model to evaluate performance and optimize efficiency. It is often desirable to measure the throughput of a model. In order to provide this Notermation out of the box, Cerebras Model Zoo runs print a couple of throughput metrics to the console as well as sending them to events files that are then viewable in TensorBoard. This section describes what these metrics are, how they are calculated, and intricacies to be aware of when interpreting them. ### Instant Throughput Measurement with Cerebras Model Zoo There are two throughput metrics that are printed to the console by default when running a model using Cerebras Model Zoo. These are `Rate` and `GlobalRate`. It is important to note that these metrics are what’s measured by the user node. While they are useful for getting an overall picture of throughput, they are not exact measurements of throughput seen by the Cerebras Wafer-Scale Cluster. This is due to the asynchronous nature of execution on Cerebras Wafer-Scale, where input workers stream data to the wafer quasi-independently of the user node that’s receiving the outputs. ### GlobalRate `GlobalRate` measures average throughput over the training run, excluding the time spent writing the final checkpoint. In contrast, `total_time` includes this final checkpoint time. As a result, dividing `total_samples` by `total_time` may yield a lower value than `global_rate`, which is based on the time at which the last sample was processed It does so by dividing total samples for which outputs have been received by total time since the executable was fully loaded to the Wafer-Scale Engine. > [!NOTE] > > `GlobalRate` is also logged to events files and is viewable in TensorBoard as `avg_samples_per_sec`. ### Rate `Rate` measures a smoothed out version of `GlobalRate`, where at each sampling interval (i.e. logging step), a smoothing factor (default of 0.4) is applied to the previously calculated `Rate` and added to the local throughput since the last sampling point. > [!NOTE] > > `Rate` is also logged to events files and is viewable in TensorBoard as `local_samples_per_sec`. > [!NOTE] > > While `Rate` is more susceptible to spikes than `GlobalRate`, it is more representative of the current throughput measured by the user node. ### Ephemeral throughput spikes after checkpointing During a checkpointing step, wafer stops processing samples until a checkpoint is taken. Once checkpointing on the Wafer-Scale Cluster is complete, streaming samples from input workers is immediately resumed. However, while the WSE is processing samples post the checkpoint step, user node may still be downloading the checkpoint from the Wafer-Scale Cluster, which could take some time, especially for large checkpoints. As such, the WSE may have computed outputs for a number of samples but user node will only fetch those outputs once it has fully downloaded the checkpoint. As a result, once checkpointing on the user node is complete and it starts fetching outputs from the Wafer-Scale Cluster, a large number of outputs may be readily available for fetching, which could result in a large spike in local throughput (i.e., `Rate`) seen. Once user node catches up to the wafer, throughput will stabalize and return to normal. > [!NOTE] > > This effect is less pronounced in `GlobalRate` when doing long training runs since it’s amortized over the entire training duration. ### Throughput in Weight Streaming execution In Weight Streaming execution, outputs (such as losses, summaries, etc.) are received as soon their values have been computed by the wafer (except after a checkpointing step, as described above). As such, there’s a close one-to-one correspondence between the throughput achieved by the wafer vs. what the user node sees (i.e., `Rate` and `GlobalRate`). Having said that, the first few logging steps may present outlier throughputs due to difference in when the clock is started on the user node vs. when the wafer actually starts processing data. This effect is short-lived and steady-state throughput is achieved quickly thereafer. ## Conclusion Accurately measuring the throughput of a model using the Cerebras Model Zoo provides vital insights into the performance and efficiency of the model on the Wafer-Scale Engine. The two key metrics, Rate and GlobalRate, offer a snapshot of instant and average throughput, respectively, aiding in the overall assessment of the model’s execution speed. It’s crucial to understand the nuances of these measurements, including their susceptibility to spikes during checkpointing and the influence of weight streaming on throughput visibility. By monitoring these metrics, users can gain a comprehensive understanding of their model’s performance, facilitating optimizations and ensuring effective utilization of the Wafer-Scale Engine’s capabilities. # Fine-Tune Your First Model Source: https://training-docs.cerebras.ai/rel-2.5.0/getting-started/fine-tune-your-first-model Follow this guide to fine-tune your first model on a Cerebras system. ## Overview This tutorial teaches you about Cerebras essentials like data preprocessing and training scripts, config files, and checkpoint conversion tools. To understand these concepts, you’ll fine-tune [Meta’s Llama 3 8B](https://huggingface.co/meta-llama/Meta-Llama-3-8B) on a small dataset consisting of documents and their summaries. In this quickstart guide, you will: * Setup your environment * Pre-process a small dataset * Port a trained model from Hugging Face * Fine-tune and evaluate a model * Test your model on downstream tasks * Port your model to Hugging Face > [!NOTE] > > In this tutorial, you will train your model for a short while on a small dataset. A high quality model requires a longer training run, as well as a much larger dataset. ## Prerequisites To begin this guide, you must have: * Cerebras system access. If you don't have access, contact Cerebras Support. * Completed [setup and installation](../getting-started/setup-and-installation). ## Workflow **1. Create Model Directory & Copy Configs** First, save the working directory to an environment variable: ```Bash theme={null} export MODELZOO_PARENT=$(pwd) ``` Then, create a dedicated folder to store assets (like data and model configs) and generated files (such as processed datasets, checkpoints, and logs): ```Bash theme={null} mkdir finetuning_tutorial ``` Next, copy the sample configs into your folder. These include model configs, evaluation configs, and data configs. ```Bash theme={null} cp modelzoo/src/cerebras/modelzoo/tutorials/finetuning/* finetuning_tutorial ``` > [!NOTE] > > We use `cp` here to copy configs specifically designed for this tutorial. For general use with Model Zoo models, we recommend using `cszoo config pull`. See the [CLI command reference](../model-zoo/cli-overview#config:pull) for details. **2. Inspect Configs** Before moving on, inspect the configuration files you just copied to confirm that the parameters are set as expected. > [accordion] Model Config > > To view the model config, run: > > ```Bash theme={null} > cat pretraining_tutorial/model_config.yaml > ``` > > You should see the following content in your terminal: > > ```yaml theme={null} > ######################################## > ## Pre-Training Tutorial Model Config ## > ######################################## > > trainer: > init: > model_dir: pretraining_tutorial/model > backend: > backend_type: CSX > cluster_config: > num_csx: 1 > callbacks: > - ComputeNorm: {} > checkpoint: > steps: 18 > logging: > log_steps: 1 > loop: > eval_steps: 5 > max_steps: 18 > model: > attention_dropout_rate: 0.0 > attention_module: multiquery_attention > attention_type: scaled_dot_product > dropout_rate: 0.0 > embedding_dropout_rate: 0.0 > embedding_layer_norm: false > extra_attention_params: > num_kv_groups: 8 > filter_size: 14336 > fp16_type: cbfloat16 > hidden_size: 4096 > initializer_range: 0.02 > layer_norm_epsilon: 1.0e-05 > loss_scaling: num_tokens > loss_weight: 1.0 > max_position_embeddings: 8192 > mixed_precision: true > nonlinearity: swiglu > norm_type: rmsnorm > num_heads: 32 > num_hidden_layers: 32 > pos_scaling_factor: 1.0 > position_embedding_type: rotary > rope_theta: 500000.0 > rotary_dim: 128 > share_embedding_weights: false > use_bias_in_output: false > use_ffn_bias: false > use_ffn_bias_in_attention: false > use_projection_bias_in_attention: false > vocab_size: 128256 > optimizer: > AdamW: > betas: > - 0.9 > - 0.95 > correct_bias: true > weight_decay: 0.01 > precision: > enabled: true > fp16_type: cbfloat16 > log_loss_scale: true > loss_scaling_factor: dynamic > max_gradient_norm: 1.0 > schedulers: > - CosineDecayLR: > end_learning_rate: 1.0e-05 > initial_learning_rate: 5.0e-05 > total_iters: 18 > seed: 1 > fit: > train_dataloader: > batch_size: 8 > data_dir: train_data > data_processor: GptHDF5MapDataProcessor > num_workers: 8 > persistent_workers: true > prefetch_factor: 10 > shuffle: true > shuffle_seed: 1337 > val_dataloader: &id001 > batch_size: 1 > data_dir: valid_data > data_processor: GptHDF5MapDataProcessor > num_workers: 8 > shuffle: false > validate: > val_dataloader: *id001 > validate_all: > val_dataloaders: *id001 > ``` > > These parameters specify the full architecture of the Llama 3 8B model and help define a Trainer object for training, validation, and logging semantics. > > If you are interested, learn more about model configs [here](../model-zoo/components/supported-config-parameters), or dive into how to set up flexible [training](../model-zoo/trainer-overview) and [evaluation](../model-zoo/core-workflows/downstream-validation-using-eleuther-eval-harness). You can also follow [end-to-end tutorials](../model-zoo/tutorials) for various use cases. > [accordion] Evaluation Config > > To view the evaluation config, run: > > ```Bash theme={null} > cat pretraining_tutorial/eeh_config.yaml > ``` > > You should see the following content in your terminal: > > ```Bash theme={null} > ############################################################## > ## Pre-Training Tutorial Eleuther Evaluation Harness Config ## > ############################################################## > trainer: > init: > backend: > backend_type: CSX > cluster_config: > num_csx: 1 > model: > model_name: llama > attention_dropout_rate: 0.0 > attention_module: multiquery_attention > attention_type: scaled_dot_product > dropout_rate: 0.0 > embedding_dropout_rate: 0.0 > embedding_layer_norm: false > extra_attention_params: > num_kv_groups: 8 > filter_size: 14336 > fp16_type: cbfloat16 > hidden_size: 4096 > initializer_range: 0.02 > layer_norm_epsilon: 1.0e-05 > loss_scaling: num_tokens > loss_weight: 1.0 > max_position_embeddings: 8192 > mixed_precision: true > nonlinearity: swiglu > norm_type: rmsnorm > num_heads: 32 > num_hidden_layers: 32 > pos_scaling_factor: 1.0 > position_embedding_type: rotary > rope_theta: 500000.0 > rotary_dim: 128 > share_embedding_weights: false > use_bias_in_output: false > use_ffn_bias: false > use_ffn_bias_in_attention: false > use_projection_bias_in_attention: false > vocab_size: 128256 > callbacks: > - EleutherEvalHarness: > eeh_args: > tasks: winogrande > num_fewshot: 0 > keep_data_dir: false > batch_size: 4 > shuffle: false > max_sequence_length: 8192 > num_workers: 1 > data_dir: pretraining_tutorial/eeh > eos_id: 128001 > pretrained_model_name_or_path: meta-llama/Meta-Llama-3-8B-Instruct > flags: > csx.performance.micro_batch_size: null > ``` > > This file lets you evaluate your model via the multiple choice (non-generative) eval harness task `winogrande` on a single CSX system. > > If you are interested, you can learn more about validating models using the [Eleuther](../model-zoo/core-workflows/downstream-validation-using-eleuther-eval-harness) or [BigCode Evaluation Harness](../model-zoo/core-workflows/downstream-validation-using-bigcode-eval-harness) in our documentation. > [accordion] Data Config > > To view the data config, run: > > ```Bash theme={null} > cat pretraining_tutorial/train_data_config.yaml > ``` > > You should see the following content in your terminal: > > ```yaml theme={null} > ############################################# > ## Pre-Training Tutorial Train Data Config ## > ############################################# > setup: > data: > type: "huggingface" > source: "karpathy/tiny_shakespeare" > split: "train" > mode: "pretraining" > output_dir: "pretraining_tutorial/train_data" > processes: 1 > > processing: > huggingface_tokenizer: "meta-llama/Meta-Llama-3-8B-Instruct" > write_in_batch: True > read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks:text_read_hook" > read_hook_kwargs: > data_keys: > text_key: "text" > > dataset: > use_ftfy: True > ``` > > If you are interested, you can read more about the [various parameters](../model-zoo/components/data-preprocessing/input-data-configuration) and [pre-built utilities](../model-zoo/components/data-preprocessing/data-preprocessing) for preprocessing common data formats. You can also follow end-to-end tutorials for various use cases such as [instruction fine-tuning](../model-zoo/tutorials/instruction-fine-tuning-for-llms) and [extending context lengths using position interpolation](../model-zoo/tutorials/extend-context-length-using-position-interpolation). **3. Preprocess Data** Use your data configs to preprocess your “train” and “validation” datasets: ```Bash theme={null} cszoo data_preprocess run --config finetuning_tutorial/train_data_config.yaml cszoo data_preprocess run --config finetuning_tutorial/valid_data_config.yaml ``` You should then see your preprocessed data in `finetuning_tutorial/train_data/` and `finetuning_tutorial/valid_data/` (see the `output_dir` parameter in your data configs). > [!WARNING] > > When using the Hugging Face CLI to download a dataset, you may encounter the following error: `KeyError: 'tags'` > > This issue occurs due to an outdated version of the `huggingface_hub` package. To resolve it, update the package to version 0.26.1 by running: > > `pip install --upgrade huggingface_hub==0.26.1` An example of “train” looks as follows: ```Bash theme={null} { "document": "In Wales, councils are responsible for funding..", "summary": "As Chancellor George Osborne announced...", "id": "35821725" } ``` > [accordion] Inspect Preprocessed Data (optional) > > Once you’ve preprocessed your data, you can visualize the outcome: > > ```Bash theme={null} > python $MODELZOO_DATA/tokenflow/launch_tokenflow.py \ > --output_dir finetuning_data/train_data > ``` > > In your terminal, you will see a url like [`http://172.31.48.239:5000`.](http://172.31.48.239:5000.) Copy and paste this into your browser to launch [TokenFlow](../model-zoo/components/data-preprocessing/visualization-and-debugging), a tool for interactively visualizing whether loss and attention masks were applied correctly: > > ![](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/getting-started/tokenflow_updated.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=8abdefa3a1e8fde7e748f7de5b87daf4) **4. Download Checkpoint and Configs** Create a dedicated folder for the checkpoint and configuration files you’ll be downloading from Hugging Face. ```Bash theme={null} mkdir finetuning_tutorial/from_hf ``` You can either fine-tune a model from a local pre-trained checkpoint or (as in this tutorial) from Hugging Face. First, download checkpoint and configuration files from Hugging Face using the commands below. For the purposes of this tutorial, we’ll be using [McGill’s Llama 3-8B-Web](https://huggingface.co/McGill-NLP/Llama-3-8B-Web), a finetuned Meta-Llama-3-8B-Instruct model. ```Bash theme={null} wget -P finetuning_tutorial/from_hf https://huggingface.co/McGill-NLP/Llama-3-8B-Web/resolve/main/pytorch_model.bin wget -P finetuning_tutorial/from_hf https://huggingface.co/McGill-NLP/Llama-3-8B-Web/resolve/main/config.json ``` This will save two files in the `finetuning_tutorial/from_hf` directory: * **config.json:** The model’s configuration file. * **pytorch\_model.bin:** The model’s weights. **5. Convert Checkpoint and Configs** You can now convert the files to a format compatible with Model Zoo: ```Bash theme={null} cszoo checkpoint convert --model llama --src-fmt hf --tgt-fmt cs-current --config finetuning_tutorial/from_hf/config.json finetuning_tutorial/from_hf/pytorch_model.bin ``` Your `finetuning_tutorial/from_hf` folder should now contain: * `pytorch_model_to_cs-2.3.mdl`: The converted model checkpoint. * `config_to_cs-2.3.yaml`: The converted configuration file. While you will not need to do this in this quickstart since it has already been done for you, as a final step, you will usually point `ckpt_path` in your `finetuning_tutorial/model_config.yaml` to the location of this converted checkpoint. **6. Train and Evaluate Model** Set `train_dataloader.data_dir` and `val_dataloader.data_dir` in your model config to the absolute paths of your preprocessed data: ```Bash theme={null} sed -i "s|data_dir: train_data|data_dir: ${MODELZOO_PARENT}/finetuning_tutorial/train_data|" \ finetuning_tutorial/model_config.yaml sed -i "s|data_dir: valid_data|data_dir: ${MODELZOO_PARENT}/finetuning_tutorial/valid_data|" \ finetuning_tutorial/model_config.yaml ``` Train your model by passing your updated model configs, the location of important directories, and python packages to a run script. Click [here](../fundamentals/launch-your-job) for more information. ```Bash theme={null} cszoo fit finetuning_tutorial/model_config.yaml ``` You should then see something like this in your terminal: ```Bash theme={null} Transferring weights to server: 100%|██| 1165/1165 [01:00<00:00, 19.33tensors/s] INFO: Finished sending initial weights INFO: | Train Device=CSX, Step=50, Loss=8.31250, Rate=69.37 samples/sec, GlobalRate=69.37 samples/sec INFO: | Train Device=CSX, Step=100, Loss=7.25000, Rate=68.41 samples/sec, GlobalRate=68.56 samples/sec ... ``` Once training is complete, you will find several artifacts in the `finetuning_tutorial/model` folder (see the `model_dir` parameter in your model config). These include: * Checkpoints * TensorBoard event files * Run logs * A copy of the model config #### Inspect Training Logs (optional) Monitor your training during the run or visualize TensorBoard event files afterwards: ```Bash theme={null} tensorboard --bind_all --logdir="finetuning_tutorial/model" ``` **7. Run Evaluation Tasks** After training, you can test your model on downstream tasks: ```Bash theme={null} cszoo lm_eval finetuning_tutorial/eeh_config.yaml --tasks=winogrande --checkpoint_path=finetuning_tutorial/model/checkpoint_18.mdl --mgmt_namespace ``` Your output logs should look something like: ```Bash theme={null} ... 2024-06-24 11:06:49,596 INFO: | EleutherAI Eval Device=CSX, GlobalStep=1, Batch=632, Rate=34.38 samples/sec, GlobalRate=34.34 samples/sec 2024-06-24 11:06:49,625 INFO: | EleutherAI Eval Device=CSX, GlobalStep=1, Batch=633, Rate=34.39 samples/sec, GlobalRate=34.35 samples/sec 2024-06-24 11:07:04,333 INFO: (None), gen_kwargs: ({'temperature': None, 'top_k': None, 'top_p': None, 'max_tokens': None}), limit: None, num_fewshot: None, batch_size: None 2024-06-24 11:07:04,696 INFO: | Tasks |Version|Filter|n-shot|Metric|Value | |Stderr| |----------|------:|------|-----:|------|-----:|---|-----:| |winogrande| 1|none | 0|acc |0.7284|± |0.0141| ``` **8. Port Model to Hugging Face** Once you train (and evaluate) your model, you can [port it](../model-zoo/migration/port-a-trained-and-fine-tuned-model-to-hugging-face) to Hugging Face to generate outputs: ```Bash theme={null} cszoo checkpoint convert --model llama --src-fmt cs-auto --tgt-fmt hf --config finetuning_tutorial/model_config.yaml --output-dir finetuning_tutorial/to_hf finetuning_tutorial/model/checkpoint_0.mdl ``` This will create both Hugging Face config files and a converted checkpoint under `finetuning_tutorial/to_hf`. **9. Validate checkpoint and configs (optional)** You can now generate outputs using Hugging Face: ```Bash theme={null} pip install 'transformers[torch]' ``` ```Bash theme={null} python ``` ```Bash theme={null} Python 3.8.16 (default, Mar 18 2024, 18:27:40) [GCC 8.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig >>> from transformers import pipeline >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct") >>> config = AutoConfig.from_pretrained("finetuning_tutorial/to_hf/model_config_to_hf.json") >>> model = AutoModelForCausalLM.from_pretrained(pretrained_model_name_or_path="finetuning_tutorial/to_hf/checkpoint_0_to_hf.bin", config = config) >>> text = "Generative AI is " >>> pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) >>> generated_text = pipe(text, max_length=50, do_sample=False, no_repeat_ngram_size=2, eos_token_id=pipeline.tokenizer.eos_token_id, pad_token_id=pipeline.tokenizer.eos_token_id)[0] >>> print(generated_text['generated_text']) >>> exit() ``` > [!NOTE] > > As a reminder, in this quickstart, you did not train your model for very long. A high quality model requires a longer training run, as well as a much larger dataset. ## Conclusion Congratulations! In this tutorial, you followed an end-to-end workflow to fine-tune a model on a Cerebras system and learn about essential tools and scripts. As part of this, your learned how to: * Setup your environment * Pre-process a small dataset * Port a trained model from Hugging Face * Fine-tune and evaluate a model * Test your model on downstream tasks * Port your model to Hugging Face ## What’s Next? * Learn more about [data preprocessing](../model-zoo/components/data-preprocessing/data-preprocessing) * Learn more about the [Cerebras Model Zoo](../model-zoo/model-zoo-overview) and the different models we support # Get Started with Cerebras Source: https://training-docs.cerebras.ai/rel-2.5.0/getting-started/overview Learn how to start training models on the Cerebras Wafer-Scale Cluster. ## What's New in 2.5? * [**DINOv2 Now Available**](/rel-2.5.0/model-zoo/models/vision/dino-v2): Train and fine-tune DINOv2, a powerful self-supervised vision model for high-quality image representations without labeled data. * **Major Performance Improvements**: Experience up to **77x speedup** in checkpointing and weight initialization. * [**S3 Checkpointing**](/rel-2.5.0/model-zoo/migration/s3-checkpoints): Save and manage model checkpoints using any S3-compatible storage for seamless remote training and distributed workflows. * [**Automatic Job Restart**](/rel-2.5.0/model-zoo/automatic-job-restart): Recover from intermittent failures automatically with checkpoint-based job restarts, ensuring uninterrupted training. And many more updates! Read more in our [release notes](../release-notes/release-notes-tabs). > [card] [Getting Started](../getting-started/setup-and-installation) > > Setup and install your training environment. > [card] [Core Concepts](../concepts/cerebras-wafer-scale-cluster) > > Learn more about our Wafer-Scale Cluster. > [card] [Model Zoo](../model-zoo/model-zoo-overview) > > Explore our comprehensive repo of deep learning models optimized for the Cerebras hardware. > [card] [Cs Torch API](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/index.html) > > Functions and data structures you can use to configure and execute PyTorch models on a Cerebras cluster. # Pretrain Your First Model Source: https://training-docs.cerebras.ai/rel-2.5.0/getting-started/pre-train-your-first-model Follow this guide to pretrain your first model on a Cerebras system. ## Overview This tutorial introduces you to Cerebras essentials, including data preprocessing, training scripts, configuration files, and checkpoint conversion tools. You'll learn these concepts by pretraining [Meta’s Llama 3 8B](https://huggingface.co/meta-llama/Meta-Llama-3-8B) on [40,000 lines of Shakespeare](https://huggingface.co/datasets/karpathy/tiny_shakespeare). In this quickstart, you will: * Set up your environment * Preprocess a small dataset * Pretrain and evaluate a model * Convert your model checkpoint for Hugging Face > [!NOTE] > > In this tutorial, you will train your model for a short while on a small dataset. A high quality model requires a longer training run, as well as a much larger dataset. ## Prerequisites To begin this guide, you must have: * Cerebras system access. If you don’t have access, contact Cerebras Support. * Completed [setup and installation](../getting-started/setup-and-installation). ## Workflow **1. Create Model Directory & Copy Configs** First, save the working directory to an environment variable: ```Bash theme={null} export MODELZOO_PARENT=$(pwd) ``` Then, create a dedicated folder to store assets (like data and model configs) and generated files (such as processed datasets, checkpoints, and logs): ```Bash theme={null} mkdir pretraining_tutorial ``` Next, copy the sample configs into your folder. These include model configs, evaluation configs, and data configs. ```Bash theme={null} cp modelzoo/src/cerebras/modelzoo/tutorials/pretraining/* pretraining_tutorial ``` > [!NOTE] > > We use `cp` here to copy configs specifically designed for this tutorial. For general use with Model Zoo models, we recommend using `cszoo config pull`. See the [CLI command reference](../model-zoo/cli-overview#config:pull) for details. **2. Inspect Configs** Before moving on, inspect the configuration files you just copied to confirm that the parameters are set as expected. > [accordion] Model Config > > To view the model config, run: > > ```Bash theme={null} > cat pretraining_tutorial/model_config.yaml > ``` > > You should see the following content in your terminal: > > ```yaml theme={null} > ######################################## > ## Pretraining Tutorial Model Config ## > ######################################## > > trainer: > init: > model_dir: pretraining_tutorial/model > backend: > backend_type: CSX > cluster_config: > num_csx: 1 > callbacks: > - ComputeNorm: {} > checkpoint: > steps: 18 > logging: > log_steps: 1 > loop: > eval_steps: 5 > max_steps: 18 > model: > attention_dropout_rate: 0.0 > attention_module: multiquery_attention > attention_type: scaled_dot_product > dropout_rate: 0.0 > embedding_dropout_rate: 0.0 > embedding_layer_norm: false > extra_attention_params: > num_kv_groups: 8 > filter_size: 14336 > fp16_type: cbfloat16 > hidden_size: 4096 > initializer_range: 0.02 > layer_norm_epsilon: 1.0e-05 > loss_scaling: num_tokens > loss_weight: 1.0 > max_position_embeddings: 8192 > mixed_precision: true > nonlinearity: swiglu > norm_type: rmsnorm > num_heads: 32 > num_hidden_layers: 32 > pos_scaling_factor: 1.0 > position_embedding_type: rotary > rope_theta: 500000.0 > rotary_dim: 128 > share_embedding_weights: false > use_bias_in_output: false > use_ffn_bias: false > use_ffn_bias_in_attention: false > use_projection_bias_in_attention: false > vocab_size: 128256 > optimizer: > AdamW: > betas: > - 0.9 > - 0.95 > correct_bias: true > weight_decay: 0.01 > precision: > enabled: true > fp16_type: cbfloat16 > log_loss_scale: true > loss_scaling_factor: dynamic > max_gradient_norm: 1.0 > schedulers: > - CosineDecayLR: > end_learning_rate: 1.0e-05 > initial_learning_rate: 5.0e-05 > total_iters: 18 > seed: 1 > fit: > train_dataloader: > batch_size: 8 > data_dir: train_data > data_processor: GptHDF5MapDataProcessor > num_workers: 8 > persistent_workers: true > prefetch_factor: 10 > shuffle: true > shuffle_seed: 1337 > val_dataloader: &id001 > batch_size: 1 > data_dir: valid_data > data_processor: GptHDF5MapDataProcessor > num_workers: 8 > shuffle: false > validate: > val_dataloader: *id001 > validate_all: > val_dataloaders: *id001 > ``` > [accordion] Evaluation Config > > To view the evaluation config, run: > > ```Bash theme={null} > cat pretraining_tutorial/eeh_config.yaml > ``` > > You should see the following content in your terminal: > > ```Bash theme={null} > ############################################################## > ## Pretraining Tutorial Eleuther Evaluation Harness Config ## > ############################################################## > trainer: > init: > backend: > backend_type: CSX > cluster_config: > num_csx: 1 > model: > model_name: llama > attention_dropout_rate: 0.0 > attention_module: multiquery_attention > attention_type: scaled_dot_product > dropout_rate: 0.0 > embedding_dropout_rate: 0.0 > embedding_layer_norm: false > extra_attention_params: > num_kv_groups: 8 > filter_size: 14336 > fp16_type: cbfloat16 > hidden_size: 4096 > initializer_range: 0.02 > layer_norm_epsilon: 1.0e-05 > loss_scaling: num_tokens > loss_weight: 1.0 > max_position_embeddings: 8192 > mixed_precision: true > nonlinearity: swiglu > norm_type: rmsnorm > num_heads: 32 > num_hidden_layers: 32 > pos_scaling_factor: 1.0 > position_embedding_type: rotary > rope_theta: 500000.0 > rotary_dim: 128 > share_embedding_weights: false > use_bias_in_output: false > use_ffn_bias: false > use_ffn_bias_in_attention: false > use_projection_bias_in_attention: false > vocab_size: 128256 > callbacks: > - EleutherEvalHarness: > eeh_args: > tasks: winogrande > num_fewshot: 0 > keep_data_dir: false > batch_size: 4 > shuffle: false > max_sequence_length: 8192 > num_workers: 1 > data_dir: pretraining_tutorial/eeh > eos_id: 128001 > pretrained_model_name_or_path: meta-llama/Meta-Llama-3-8B-Instruct > flags: > csx.performance.micro_batch_size: null > ``` > [accordion] Data Config > > To view the data config, run: > > ```Bash theme={null} > cat pretraining_tutorial/train_data_config.yaml > ``` > > You should see the following content in your terminal: > > ```yaml theme={null} > ############################################# > ## Pretraining Tutorial Train Data Config ## > ############################################# > setup: > data: > type: "huggingface" > source: "karpathy/tiny_shakespeare" > split: "train" > mode: "pretraining" > output_dir: "pretraining_tutorial/train_data" > processes: 1 > > processing: > huggingface_tokenizer: "meta-llama/Meta-Llama-3-8B-Instruct" > write_in_batch: True > read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks:text_read_hook" > read_hook_kwargs: > data_keys: > text_key: "text" > > dataset: > use_ftfy: True > ``` **3. Preprocess Data** Use your data configs to preprocess your “train” and “validation” datasets: ```Bash theme={null} cszoo data_preprocess run --config pretraining_tutorial/train_data_config.yaml cszoo data_preprocess run --config pretraining_tutorial/valid_data_config.yaml ``` You should then see your preprocessed data in `pretraining_tutorial/train_data/` and `pretraining_tutorial/valid_data/` (see the `output_dir` parameter in your data configs). > [!WARNING] > > When using the Hugging Face CLI to download a dataset, you may encounter the following error: `KeyError: 'tags'` > > This issue occurs due to an outdated version of the `huggingface_hub` package. To resolve it, update the package by running: > > `pip install --upgrade huggingface_hub==0.26.1` An example of a “train” dataset looks as follows: ```Bash theme={null} { "text": "First Citizen:\nBefore we proceed any further, hear me " } ``` If you are interested, you can read more about the [various parameters](../model-zoo/components/data-preprocessing/input-data-configuration) and [pre-built utilities](../model-zoo/components/data-preprocessing/data-preprocessing) for preprocessing common data formats. You can also follow end-to-end tutorials for various use cases such as [instruction fine-tuning](../model-zoo/tutorials/instruction-fine-tuning-for-llms) and [extending context lengths using position interpolation](../model-zoo/tutorials/extend-context-length-using-position-interpolation). > [accordion] Inspect Preprocessed Data > > Once you’ve preprocessed your data, you can visualize the outcome: > > ```Bash theme={null} > python $MODELZOO_PARENT/modelzoo/src/cerebras/modelzoo/data_preparation/data_preprocessing/tokenflow/launch_tokenflow.py \ > --output_dir pretraining_tutorial/train_data > ``` > > In your terminal, you will see a url like [`http://172.31.48.239:5000.`](http://172.31.48.239:5000) Copy and paste this into your browser to launch [TokenFlow](../model-zoo/components/data-preprocessing/visualization-and-debugging), a tool for interactively visualizing whether loss and attention masks were applied correctly: > > ![](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/getting-started/tokenflow_updated.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=8abdefa3a1e8fde7e748f7de5b87daf4) **4. Train and Evaluate Model** Update `train_dataloader.data_dir` and `val_dataloader.data_dir` in your model config to use the absolute paths of your preprocessed data: ```Bash theme={null} sed -i "s|data_dir: train_data|data_dir: ${MODELZOO_PARENT}/pretraining_tutorial/train_data|" \ pretraining_tutorial/model_config.yaml sed -i "s|data_dir: valid_data|data_dir: ${MODELZOO_PARENT}/pretraining_tutorial/valid_data|" \ pretraining_tutorial/model_config.yaml ``` Now you're ready to launch training. Use the cszoo fit command to submit a job, passing in your updated model config. This command automatically uses the locations and packages defined in your config. Click [here](../fundamentals/launch-your-job) for more information. ```Bash theme={null} cszoo fit pretraining_tutorial/model_config.yaml --mgmt_namespace ``` You should then see something like this in your terminal: ``` Transferring weights to server: 100%|██| 1165/1165 [01:00<00:00, 19.33tensors/s] INFO: Finished sending initial weights INFO: | Train Device=CSX, Step=50, Loss=8.31250, Rate=69.37 samples/sec, GlobalRate=69.37 samples/sec INFO: | Train Device=CSX, Step=100, Loss=7.25000, Rate=68.41 samples/sec, GlobalRate=68.56 samples/sec ... ``` Once training is complete, you will find several artifacts in the `pretraining_tutorial/model` folder (see the `model_dir` parameter in your model config). These include: * Checkpoints * TensorBoard event files * Run logs * A copy of the model config ### Inspect Training Logs Monitor your training during the run or visualize TensorBoard event files afterwards: ```Bash theme={null} tensorboard --bind_all --logdir="pretraining_tutorial/model" ``` **5. Port Model to Hugging Face** Once you train (and evaluate) your model, you can [port it](../model-zoo/migration/port-a-trained-and-fine-tuned-model-to-hugging-face) to Hugging Face to generate outputs: ```Bash theme={null} cszoo checkpoint convert --model llama --src-fmt cs-auto --tgt-fmt hf --config pretraining_tutorial/model_config.yaml --output-dir pretraining_tutorial/to_hf pretraining_tutorial/model/checkpoint_0.mdl ``` This will create both Hugging Face config files and a converted checkpoint under `pretraining_tutorial/to_hf`. **6. Validate Checkpoint and Configs** You can now generate outputs using Hugging Face: ```Bash theme={null} pip install 'transformers\[torch\]' ``` ```Bash theme={null} python ``` ```Bash theme={null} Python 3.8.16 (default, Mar 18 2024, 18:27:40) [GCC 8.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig >>> from transformers import pipeline >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct") >>> config = AutoConfig.from_pretrained("pretraining_tutorial/to_hf/model_config_to_hf.json") >>> model = AutoModelForCausalLM.from_pretrained(pretrained_model_name_or_path="pretraining_tutorial/to_hf/checkpoint_0_to_hf.bin", config = config) >>> text = "Generative AI is " >>> pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) >>> generated_text = pipe(text, max_length=50, do_sample=False, no_repeat_ngram_size=2, eos_token_id=pipeline.tokenizer.eos_token_id, pad_token_id=pipeline.tokenizer.eos_token_id)[0] >>> print(generated_text['generated_text']) >>> exit() ``` > [!NOTE] > > As a reminder, in this quickstart, you did not train your model for very long. A high quality model requires a longer training run, as well as a much larger dataset. ## Conclusion Congratulations! In this tutorial, you followed an end-to-end workflow to pretrain a model on a Cerebras system and learn about essential tools and scripts. As part of this, your learned how to: * Setup your environment * Preprocess a small dataset * Pretrain and evaluate a model * Port your model to Hugging Face ## What’s Next? * Learn how to [fine-tune your first model](../getting-started/fine-tune-your-first-model) * Learn more about [data preprocessing](../model-zoo/components/data-preprocessing/data-preprocessing) * Learn more about the [Cerebras Model Zoo](../model-zoo/model-zoo-overview) and the different models we support # Setup and Installation Source: https://training-docs.cerebras.ai/rel-2.5.0/getting-started/setup-and-installation Learn how to install Model Zoo. In this setup guide, you will: * Clone the Model Zoo repository * Setup a virtual environment * Install dependencies ## Prerequisites Before you begin, you must have access to a Cerebras system. Contact Cerebras Support for any system configuration access and concerns. ### Clone Model Zoo ``` git clone https://github.com/Cerebras/modelzoo.git ./modelzoo ``` ### Create Virtual Environment ```bash theme={null} python3.8 -m venv modelzoo_venv source modelzoo_venv/bin/activate ``` ### Install Dependencies ```bash theme={null} pip install --upgrade pip pip install --editable ./modelzoo ``` ### Verify Installation ``` cerebras_install_check --mgmt_namespace ``` ## What’s Next? * [Pretrain](../getting-started/pre-train-your-first-model) your first model. * [Fine-tune](../getting-started/fine-tune-your-first-model) your first model. * Learn the [data preprocessing](../model-zoo/core-workflows/quickstart-guide-for-data-preprocessing) basics. * Learn more about [Model Zoo](../model-zoo/model-zoo-overview). # Automatic Job Restart Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/automatic-job-restart Learn how to configure automatic job restart in your Trainer config. Automatic Job Restart enables long-running jobs to automatically recover from intermittent failures, eliminating the need for constant monitoring. This feature tracks job progress using checkpoints while monitoring restart attempts. It automatically flags faulty systems that may have caused failures and restarts from the last saved checkpoint. ## Restart Behavior When Automatic Job Restart is enabled: * The system resets the failure count when a run makes progress (i.e., captures a new checkpoint). * For multiphase trainer configurations, each trainer config runs sequentially with autorestart. Subsequent configs only run if the previous one succeeds. ## Prerequisites Before using Automatic Job Restart, ensure that [Checkpointing](../model-zoo/components/trainer-components/checkpointing) is configured. Restarts will commence from the last-saved checkpoint. ## Configuration Add the `autorestart` parameter to your Trainer config file: ```yaml theme={null} trainer: init: # Your existing configuration autorestart: max_num_restarts: 3 # Required: Maximum number of automatic restarts min_num_csx: 1 # Optional: Minimum number of CSX systems (defaults to 1) ``` When you launch a training or eval job, the run will automatically restart if any recoverable failures are encountered if `max_num_restarts` is specified in the autorestart config. Learn more about launching jobs [here](../fundamentals/launch-your-job). ### Parameters * `max_num_restarts`: The maximum number of automatic restarts allowed without any progress (new checkpoints) before the run is considered failed. This parameter is required. * (Optional) `min_num_csx`: The minimum number of CSX systems with which to perform a restart. Defaults to 1 if not specified. In the event of a faulty system in the cluster, this feature will automatically remove that system from the usable pool and, unless a replacement system is found, restart with the remaining number of systems. This config establishes a lower bound on the number of systems from the usable pool with which to perform a restart. If a redundant pool is required to ensure that a job has adequate resources in case of a faulty system, learn how to create one [here](../cluster-monitoring/cerebras-job-scheduling-and-monitoring/cli-for-job-monitoring-csctl#redundancy-pools). ## Log Files and Monitoring Restart logs are stored in `/model_dir/_restartable/run.log`. For multiphase trainer configs, each phase will have a separate timestamped restartable directory. > [!NOTE] > > When automatic restart is enabled, the system will prefetch extra compile jobs in the background for `num_csx - 1` and `num_csx - 2` system configurations. As a result, you may see log messages like this: > > `[restartable_trainer.py:319] Prefetching compile for num_csx=1 completed successfully.` > > \ > This helps speed up restarts after system failures and no action is required. ## Limitations * Validation runs will only restart from scratch in the event of failures. * During training and eval runs, if a failure occurs during validation, restart will resume from the next training loop. * If a dataloader loads tokens out of bounds of the model's `vocab_size`, the system will exhaust `max_num_restarts` before failing. * The system cannot automatically restart runs that are deadlocked at the system level. ### Non-Recoverable Failures The following errors will not trigger automatic restarts, regardless of how many `max_num_restarts` you've specified: * Compilation or lowering failures * Invalid user configurations * Failed assertions in Model Zoo # CLI Overview Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/cli-overview Learn how to use the ModelZoo CLI. ## Overview The ModelZoo CLI is a comprehensive command-line interface that serves as a single entry point for all ModelZoo-related tasks. This tool streamlines various machine learning workflows, from data preprocessing to model training and validation. ## Commands Below is a list of commands that can be used with the ModelZoo CLI tool. Expand each section to see examples and more information. > [accordion] fit > > Trains a model using specified configuration > > Example: `cszoo fit params_model.yaml` > [accordion] validate > > Validates a model using specified configuration > > Example: `cszoo validate params_model.yaml` > [accordion] validate\_all > > Runs upstream and downstream validation > > Example: `cszoo validate_all params_model.yaml` > [accordion] checkpoint > > Checkpoint converter > > > [accordion] convert > > > > Converts a checkpoint between Huggingface and Cerebras formats or between different Cerebras formats. > > > > Example: `cszoo checkpoint convert --model gpt2 --src-fmt cs-auto --tgt-fmt hf --config workdir/params_gpt_tiny.yaml model_dir/checkpoint.mdl` > > > [accordion] convert-config > > > > Converts a checkpoint between Huggingface and Cerebras formats or between different Cerebras formats. > > > > Example: `cszoo checkpoint convert-config --model gpt2 --src-fmt cs-auto --tgt-fmt hf workdir/params_gpt_tiny.yaml` > > > [accordion] list-converters > > > > Lists all available checkpoint converters. Can also list all checkpoint converters for a specified model. > > > > Example: `cszoo checkpoint list-converters` > > > [accordion] diff > > > > Compares two checkpoints to identify differences. > > > > Example: `cszoo checkpoint diff checkpoint_a.mdl checkpoint_b.mdl` > > > [accordion] info > > > > Displays checkpoint details, including size, number of S3 sub-objects, and the software version used to save it. > > > > Example: `cszoo checkpoint info PATH` > > > [accordion] delete > > > > Deletes a checkpoint and all associated sub-objects (if stored in S3). > > > > Example: `cszoo checkpoint delete PATH` > > > [accordion] copy > > > > Copies a checkpoint between local filesystems or S3 buckets. Useful for uploading existing checkpoints from previous releases to S3. > > > > Example: `cszoo checkpoint copy SRC_PATH DST_PATH` > > > [accordion] move > > > > Moves a checkpoint between local filesystems or S3 buckets, deleting the original source after transfer. Useful for migrating older checkpoints to S3. > > > > Example: `cszoo checkpoint move SRC_PATH DST_PATH` > [accordion] model > > Query information on ModelZoo models > > > [accordion] list > > > > Displays all supported models. > > > > Example: `cszoo model list` > > > [accordion] info > > > > Shows detailed model information. > > > > Example: `cszoo model info llama` > > > [accordion] describe > > > > Displays model configuration parameters. > > > > Example: `cszoo model describe llama` > > > [accordion] init\_checkpoint > > > > Creates initial model checkpoint. > > > > Example: `cszoo model init_checkpoint ` > [accordion] data\_preprocess > > Preprocess data > > > [accordion] list > > > > Shows available preprocessing configurations. > > > > Example: `cszoo data_preprocess list` > > > [accordion] pull > > > > Copies a model configuration file to a local directory. > > > > Example: `cszoo data_preprocess pull summarization_preprocessing -o workdir` > > > [accordion] run > > > > Executes preprocessing using specified configuration. > > > > Example: `cszoo data_preprocess run --config preprocessing.yaml` > [accordion] data\_processor > > Query information on ModelZoo data processors > > > [accordion] list > > > > Shows available data processors. > > > > Example: `cszoo data_processor list` > > > [accordion] info > > > > Displays data processor information. > > > > Example: `cszoo data_processor info GptHDF5DataProcessor` > > > [accordion] describe > > > > Shows processor configuration parameters. > > > > Example: `cszoo data_processor describe GptHDF5DataProcessor` > > > [accordion] benchmark > > > > Benchmarks a specified dataloader. > > > > Example: `cszoo data_processor benchmark params.yaml` > [accordion] config > > Save and manage model config files > > > [accordion] pull > > > > Copies a model config file to a local directory. > > > > Example: `cszoo config pull llama2_7b -o workdir` > > > [accordion] validate > > > > Validates a specified config file. > > > > Example: `cszoo config validate params.yaml` > > > [accordion] convert\_legacy > > > > Upgrades V1 config files to V2 YAML. > > > > Example: `cszoo config convert_legacy old_config.yaml` > > > [accordion] stats > > > > Retrieves relevant statistics for a model using the specified configuration file. > > > > Example: `cszoo config stats params.yaml` > [accordion] lm\_eval > > Runs evaluation using the Eleuther Eval Harness. > > Example: `cszoo lm_eval workdir/params_gpt_tiny.yaml --tasks=winogrande --checkpoint_path=workdir/my_ckpt.mdl` > [accordion] bigcode\_eval > > Runs code generation benchmarks using the BigCode Eval Harness. > > Example: `cszoo bigcode_eval workdir/params_gpt_tiny.yaml --tasks=mbpp --checkpoint_path=workdir/my_ckpt.mdl` ## Example Workflow: Pretraining a model using the ModelZoo CLI This workflow guides you through the steps to pretrain a model using the Cerebras ModelZoo CLI. Follow these steps to set up your environment, preprocess data, and run the pretraining process. > [!TIP] > > **Prerequisite:** Before proceeding with the steps below, ensure that you have completed the setup and installation guide found [here](../getting-started/setup-and-installation). **1. Create model directory** Create a directory to store all the files for this pretraining workflow and copy the necessary configuration files. ``` mkdir pretraining_tutorial cp modelzoo/src/cerebras/modelzoo/tutorials/pretraining/* pretraining_tutorial ``` **2. Preprocess the data** Preprocess the training and validation datasets using the provided configuration files. ```bash theme={null} cszoo data_preprocess run --config pretraining_tutorial/train_data_config.yaml cszoo data_preprocess run --config pretraining_tutorial/valid_data_config.yaml ``` **3. Run model** Run the pretraining process using the provided configuration. ``` cszoo fit pretraining_tutorial/model_config.yaml ``` **4. Convert checkpoint to HuggingFace** Convert the trained model checkpoint into a HuggingFace-compatible format. ``` cszoo checkpoint convert \ --model llama \ --src-fmt cs-auto \ --tgt-fmt hf \ --config pretraining_tutorial/model_config.yaml \ --output-dir pretraining_tutorial/to_hf \ pretraining_tutorial/model/checkpoint_0.mdl ``` ## Getting Help For detailed information about any command, use the `--help` flag: ``` cszoo --help cszoo --help ``` ### CSZoo Assistant Need help? Our CSZoo Assistant is an LLM agent you can access from the command line with the `assistant` subcommand. Use it to: * Ask questions: `cszoo assistant "what is the checkpoint converter?"` * Perform actions: `cszoo assistant "convert my checkpoint from huggingface to cerebras"` CSZoo Assistant will always ask your permission before running a command. > [!NOTE] > > Access to the Cerebras Inference API is required and you'll need to provide your API key with the following command: > > `export CEREBRAS_API_KEY=` > > Don't have an API key? Follow [these instructions](https://inference-docs.cerebras.ai/quickstart#step-1-set-up-your-api-key). > [!WARNING] > > CSZoo Assistant is a beta feature and it may make mistakes. Always double-check its reasoning and be aware of the following limitations: > > * CSZoo Assistant can currently only access the help manuals found with `cszoo ... -h`. > > * There are currently no advanced context length management mechanisms in place. The assistant will error out if it overflows the context length. # Data Deduplication Pipeline Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/data-deduplication-pipeline Learn how to set up and run a deduplication pipeline on the Cerebras platform. Data deduplication is a crucial step in managing large-scale datasets, ensuring data quality, and optimizing storage. The data deduplication tool is designed to remove redundant data from text datasets to improve model training quality and efficiency. The pipeline consists of several stages, which our `dedup.py` script executes: 1. MinHash generation 2. duplicate pairs generation 3. duplicate graph construction 4. generating the final list of duplicates If needed, you can run each stage of the pipeline individually. See [Manual Instructions](#optional-manual-instructions) for more details. To optimize the deduplication process, we leverage the [datasketch library](http://ekzhu.com/datasketch/minhash.html) for efficient similarity detection and incorporate enhancements to address memory usage and runtime performance. Our approach implements a **producer-consumer model** to parallelize I/O operations, which are the primary bottleneck in runtime. Additionally, memory consumption is minimized by retaining only a single representative document from each group of duplicates in memory at any given time, ensuring efficient resource utilization during processing. ## Before You Begin Ensure the Cerebras Model Zoo and its dependencies are [installed](../../getting-started/setup-and-installation) if you're running on a *Cerebras Wafer-Scale cluster* (specifically the prerequisites listed [here](https://github.com/Cerebras/modelzoo/blob/main/requirements.txt)). If you'd like to run this *locally*, do the following: ```bash theme={null} virtualenv source /bin/activate pip install -r requirements.txt ``` ## Run the Script To run the deduplication pipeline, execute the following command: ```bash theme={null} python dedup.py --dataset_name --input_dir --jsonl_key --format --output_dir ``` The process generates an output directory containing compressed `.jsonl.zst` files. By default, each compressed file will be of size 16 MB, and the `jsonl_key` will be `text`. ## (Optional) Manual Instructions While the `dedup.py` script runs the deduplication pipeline end-to-end, you can also run each stage individually if needed. ### MinHash Generation MinHash generation can be a very slow process. We recommend running it separately before creating a MinHashLSH index. To calculate MinHash object for each document, we strip, lowercase, remove punctuation, consecutive spaces, newlines and tabs from each document. Afterwards, we construct a list of 13-grams that are later used as features to create a document signature to add into MinHashLSH index. (More details about MinHash can be found at [Identifying and Filtering Near-Duplicate Documents](https://cs.brown.edu/courses/cs253/papers/nearduplicate.pdf).) We also apply NFC normalization, as well as filter out short documents, before yielding the documents. > [!NOTE] > > For custom datasets, you also need to specify the `jsonl_key` as well as the format of the dataset. By default, the `jsonl_key` is set to be `text` and the format to be `jsonl`. Here is the format of the command to run MinHash generation: ```bash theme={null} python to_hash.py --dataset_name --input_dir --output_dir --job_id --jsonl_key --format ``` To reduce the total processing time, multiple jobs can be run for each corpus in parallel by using multiple job IDs - starting from 0. By default, the script works expecting one job, but if you wish, you can replicate the scripts across multiple machines and the script chunks the list of files to be processed equally, to do the MinHash generation. > [!NOTE] > > This assumes that the dataset is present at a common place that is accessible by all the machines. ### Duplicate Pairs Generation In this step, we build a MinHashLSH index and query it to locate near duplicates (More reading here: [Chapter 3, Mining of Massive Datasets](http://infolab.stanford.edu/~ullman/mmds/ch3.pdf). ) We use a Jaccard similarity threshold of 0.8 by default to determine whether a pair of documents should be considered as a duplicate, but you can specify it according to your own needs. ```bash theme={null} python generate_duplicate_pairs.py --input_dir --out_file /duplicates/duplicate_pairs.txt ``` ### Duplicate Graph Construction & Search for Connected Components After locating duplicate pairs, we need to find connected components containing documents that are duplicates with each other. To make it more illustrative, consider these pairs: (A, B), (A, C), (A, E). We are going to form a cluster of (A, B, C, E) and keep only one document from the component. We evaluated the performance and memory consumption of [networkx](https://networkx.org/), [graphtool](https://graph-tool.skewed.de/), and [networkit](https://networkit.github.io/). `networkit` offered most efficient implementation as it is designed to work with large graphs and features great parallelism. Below you can find an example command how to construct a graph from documents pairs: ```bash theme={null} python generate_connected_components.py --input_dir /duplicates/connected_components.pickle ``` ### Generate Final List of Duplicates In this step, we generate the final deduplicated dataset. We dump the original dataset in fixed-size files, in the `jsonl.zst` format, whose size is configurable in the `deduplicate_dataset.py` file. By default, we create files of 16 MB. Below you can find an example command on how to generate the final deduplicated dataset: ```bash theme={null} python deduplicate_dataset.py --input_file /duplicates/connected_components.pickle --input_dir --output_dir --format ``` # Custom Tokenizer Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/data-preprocessing/custom-tokenizer Learn how to initialize a custom tokenizer to better handle domain-specific vocabulary or capture nuances that standard tokenizers miss. In the `processing` section of your config file, specify the path to the custom token tokenizer class in the `custom_tokenizer` parameter. If needed, pass in additional `tokenizer_params` (such as `token`, `vocab_file`, or `encoder_file`). For example: ```yaml theme={null} processing: custom_tokenizer: "path.to.module:tokenizer_class" tokenizer_params: token: "" vocab_file: "" encoder_file: "" ``` > [!NOTE] > > The path to your custom tokenizer must be specified using this format: `module_name:class_name`. ## Example of a Custom Tokenizer Here is an example of custom LLama3 tokenizer that was implemented in Model Zoo: ```python theme={null} from functools import wraps from typing import Any, Dict, List, Tuple, Union from transformers import AutoTokenizer class CustomLlama3Tokenizer: def __init__( self, pretrained_model_name_or_path: str, eos_token_id: Union[int, None] = None, pad_token_id: Union[int, None] = None, **kwargs: Any, ): """ Custom implementation of Llama3 Tokenizer, which overrides compute_offsets of the Hugging Face. Args: pretrained_model_name_or_path (str): The pretrained model name or path. eos_token_id (Union[int, None], optional): The ID of the end-of-sequence token. Defaults to None. pad_token_id (Union[int, None], optional): The ID of the padding token. Defaults to None. **kwargs (Any): Additional keyword arguments to be passed to AutoTokenizer. Attributes: tokenizer (AutoTokenizer): The AutoTokenizer instance for the given pretrained model. eos_token_id (int): The ID of the end-of-sequence token. pad_token_id (int): The ID of the padding token. """ self.tokenizer = AutoTokenizer.from_pretrained( pretrained_model_name_or_path, **kwargs ) self.eos_token_id = ( eos_token_id if eos_token_id is not None else self.tokenizer.eos_token_id ) self.pad_token_id = ( pad_token_id if pad_token_id is not None else self.eos_token_id ) def compute_offsets( self, encoded: Dict[str, Any], return_offsets_mapping: bool = False ) -> List[Tuple[int, int]]: """ Compute offsets for the given encoded input. Args: encoded (Dict[str, Any]): The encoded input containing 'input_ids' and 'offset_mapping'. return_offsets_mapping (bool, optional): Whether to return the offsets mapping. Defaults to False. Returns: List[Tuple[int, int]]: A list of tuples representing the start and end offsets for each token. """ input_ids = encoded['input_ids'] offset_mapping = encoded['offset_mapping'] for i, (input_id, (start, end)) in enumerate( zip(input_ids, offset_mapping) ): token = self.tokenizer.convert_ids_to_tokens(input_id) if input_id not in self.tokenizer.all_special_ids: offset_mapping[i] = (start, start + len(token)) return offset_mapping def __call__(self, text: str, **kwargs: Any) -> Dict[str, Any]: """ Encode the given text into tokens and optionally return the offsets mapping. Args: text (str): The input text to tokenize. **kwargs (Any): Additional keyword arguments for tokenization. Returns: Dict[str, Any]: The encoded result containing 'input_ids', 'attention_mask', and optionally 'offset_mapping'. """ return_offset_mapping = kwargs.get('return_offsets_mapping') encoded = self.tokenizer(text, **kwargs) if return_offset_mapping: fixed_offsets = self.compute_offsets( encoded, return_offsets_mapping=return_offset_mapping ) encoded['offset_mapping'] = fixed_offsets return encoded def __getattr__(self, name: str) -> Any: """ Forward attribute access to the underlying tokenizer. Args: name (str): The name of the attribute to access. Returns: Any: The attribute value. """ attr = getattr(self.tokenizer, name) if callable(attr): @wraps(attr) def wrapper(*args, **kwargs): return attr(*args, **kwargs) return wrapper return attr def __len__(self) -> int: """ Get the vocabulary size of the tokenizer. Returns: int: The vocabulary size. """ return self.tokenizer.vocab_size ``` View this code in the [Model Zoo](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/data_preparation/data_preprocessing/custom_tokenizer_example). # Dataset Splitting and Preprocessing Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/data-preprocessing/data-context-splits Learn how to split and preprocesses datasets for LLM training. You can organize your data in two ways: * **Single Dataset**: All files in one input directory * **Multiple Subsets**: Files organized in separate subdirectories ## Setting Up Your Dataset ### Option 1: Single Dataset Setup Place all your data files in one directory: ``` input_dir/ ├── file1.jsonl.zst ├── file2.jsonl.zst ``` ### Option 2: Multiple Subsets Setup Organize files into subdirectories that represent different subsets: ``` input_dir/ ├── subset_1/ │ ├── file1.jsonl.zst ├── subset_2/ │ ├── file2.jsonl.zst ``` ## Configuration Options ### Basic Configuration Your configuration file needs these essential parameters: ```yaml theme={null} setup: data: source: "./input_dir" # Path to your input data type: "local" # Data source type output_dir: "./output_dir" # Where processed data will be stored data_splits_dir: "./data_splits" # Directory for split datasets ``` ### Defining Data Splits You can split your dataset in two ways: 1. **Data Splits Only** - Divide your data into train/validation/test sets: ```yaml theme={null} data_splits: train: split_fraction: 0.8 # 80% of data goes to training val: split_fraction: 0.2 # 20% of data goes to validation ``` 2. **Context Splits Only** - Split by maximum sequence length: ```yaml theme={null} context_splits: MSL_List: [128, 512] # Sequence length options split_fractions: [0.5, 0.5] # Distribution between lengths ``` 3. **Combined Splits** - Split by both data type and sequence length: ```yaml theme={null} data_splits: train: split_fraction: 0.8 context_splits: MSL_List: [128, 512] split_fractions: [0.5, 0.5] val: split_fraction: 0.2 context_splits: MSL_List: [128, 512] split_fractions: [0.6, 0.4] ``` ### Multiple Subsets Configuration To process multiple subsets, add this to your configuration: ```yaml theme={null} setup: data: source: "./input_dir" type: "local" top_level_as_subsets: True # Process each subdirectory as a separate dataset ``` ## How Splitting Works ### Random Sampling Process The system uses deterministic random sampling to assign documents to splits: 1. For data splits: Each document is randomly assigned to train/val/test based on the `split_fraction` values 2. For context splits: Each document is assigned a maximum sequence length from the `MSL_List` based on `split_fractions` 3. For combined splits: A two-level sampling process first assigns the data split, then the context length For reproducibility, all sampling uses a fixed random seed that you can set: ```yaml theme={null} processing: split_seed: 42 # Set your own seed for reproducible results ``` ### Output Structure After processing, your output directory will contain: **For a single dataset:** ``` output_dir/ ├── train/ │ ├── msl_128/ # Contains files processed with 128 max sequence length │ └── msl_512/ # Contains files processed with 512 max sequence length └── val/ ├── msl_128/ └── msl_512/ ``` **For multiple subsets:** ``` output_dir/ ├── subset_1/ │ ├── train/ │ │ ├── msl_128/ │ │ └── msl_512/ │ └── val/ │ ├── msl_128/ │ └── msl_512/ ├── subset_2/ │ ├── train/ │ └── val/ ``` ## Complete Configuration Example ```yaml theme={null} setup: data: source: "./input_dir" type: "local" top_level_as_subsets: True # Remove this line for single dataset processing output_dir: "./output_dir" data_splits_dir: "./data_splits" data_splits: train: split_fraction: 0.8 context_splits: MSL_List: [128, 512] split_fractions: [0.5, 0.5] val: split_fraction: 0.2 context_splits: MSL_List: [128, 512] split_fractions: [0.6, 0.4] processing: split_seed: 42 # Additional processing parameters go here ``` # Configure Data Preprocessing Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/data-preprocessing/data-preprocessing Learn how to preprocess your data into HDF5 format for pretraining, finetuning, and custom processing tasks. We’ll walk through configuring the YAML file used to define your preprocessing setup, including how to specify input data, set processing parameters, and initialize tokenizers. > [!TIP] > > Ready to jump into data preprocessing? Check out our [quickstart guide](../model-zoo/core-workflows/quickstart-guide-for-data-preprocessing). The configuration is made up of three main sections: * `setup`: Environment configuration parameters * `processing`: Common preprocessing parameters * `dataset`: Task-specific or token generator parameters Refer to the sections below for more details. > [!TIP] > > Refer to example configuration files [here](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/data_preparation/data_preprocessing/configs). ## Setup Section Use the setup section to configure the environment and parameters required for processing tasks. This is where you'll specify the output directory, image directory (for multimodal tasks), input file handling, set the number of processes, and choose the preprocessing mode. 1. `output_dir ` specifies the directory where output files will be saved. * Default: `./output/` if not explicitly set. * This directory is essential for storing all generated output files. 2. `image_dir` determines the directory path where image files will be saved for multimodal tasks. Used only when `is_multimodal` is True in the `dataset` section. 3. `data` configures input data handling, including data source and format. Learn more about using these parameters to configure input data in our [Configure Input Data guide](../data-preprocessing/input-data-configuration). * `source`: * For local data, this defines the directory path containing input files and is mandatory. * For Hugging Face datasets, this specifies the dataset name from the Hugging Face hub. * `type` specifies how the input data is accessed: * `local`: Reads data from a specified directory. Supported file formats for local data: `.jsonl`, `.json.gz`, `.jsonl.zst`, `.jsonl.zst.tar`, `.parquet`, `.txt`, and `.fasta`. * `huggingface`: Loads datasets using Hugging Face's `load_dataset` function with additional parameters. * `top_level_as_subsets`: If `True`, all top-level directories in your `source` (if using local data) are processed as separate datasets. Defaults to `False` if not specified. * `subsets`: To process only specific subdirectories in your `source` (if using local data), provide a list of those directories (`subsets: ["subset_1", "subset_2" ...]`). * `split` (required for Hugging Face datasets) indicates the dataset split to process (e.g., `train`, `validation`). * `kwargs` specifies additional parameters passed to the `load_dataset` function when using Hugging Face datasets. 4. `mode` specifies the processing mode (pretraining, finetuning, or others). Learn more about modes [here](#modes). 5. `processes` determines the number of processes to use for the task. Default value is `1`. If set to `0`, it automatically uses all available CPU cores for optimal performance. 6. `token_generator` (custom mode only) specifies which token generator to use. This parameter is split to extract the token generator's name, enabling the system to initialize and use the specified token generator during processing. ### Split the Dataset The setup section also supports powerful options for dividing your dataset into training, validation, and test splits, along with optional context-based splits. 7. `data_splits_dir`: Top-level directory where split datasets will be saved. 8. `data_splits`: Use this to define how your data is split across different stages (e.g., `train`, `val`, `test`). * `split_fractions`: Corresponding fractions for each MSL. Must sum to 1. ```yaml theme={null} data_splits: train: split_fraction: 0.8 val: split_fraction: 0.2 ``` 9. `context_splits`: (optional) Further divides a split (like train or val) based on Maximum Sequence Lengths (MSLs). * `MSL_List`: List of MSL values to apply. Example nested in a data split: ```yaml theme={null} data_splits: train: split_fraction: 0.8 context_splits: MSL_List: [128, 512] split_fractions: [0.5, 0.5] ``` Learn more about splitting datasets in [Dataset Splitting and Preprocessing](../../../../rel-2.5.0/model-zoo/components/data-preprocessing/data-context-splits). > [!NOTE] > > For optimal processing, it is recommended that all files (except `.txt` files) contain a substantial amount of text within each individual file. Ideally, each file should be sized in the range of gigabytes (GB). ### Modes In the setup section of the configuration file, the mode specifies the processing approach for the dataset. It determines how dataset parameters are managed and which [token generator](../../../model-zoo/components/data-preprocessing/token-generators) is initialized: `pretraining` is used for pretraining tasks. Depending on the dataset configuration, different token generators are initialized: * If the dataset uses the `is_multimodal` parameter, it does multimodal pretraining data preprocessing. * If the training objective is “Fill In the Middle” (FIM), it initializes the `FIMTokenGenerator`. * If the `use_vsl` parameter is set to `True`, it initializes the `VSLPretrainingTokenGenerator`. Otherwise, it initializes the `PretrainingTokenGenerator`. `finetuning` is used for finetuning tasks. Depending on the dataset configuration, different token generators are initialized: * If the dataset uses the `is_multimodal` parameter, it does multimodal finetuning data preprocessing. * If the `use_vsl` parameter is set to `True`, it initializes the `VSLFinetuningTokenGenerator`. Otherwise, it initializes the `FinetuningTokenGenerator`. #### Other Modes * `dpo`: This mode initializes the `DPOTokenGenerator`. It is used for tasks that require specific processing under the `dpo` mode. * `nlg`: This mode initializes the `NLGTokenGenerator`. It is used for natural language generation tasks. * `custom`: This mode allows for user-defined processing by plugging in their own custom token generator. ## Processing Section Use the processing section to initialize parameters for preprocessing tasks and set up class attributes based on the provided configuration. **Initialization and Configuration Params** * `resume_from_checkpoint`: Boolean flag indicating whether to resume processing from a checkpoint. Defaults to `False`. * `max_seq_length`: Specifies the maximum sequence length for processing. Defaults to 2048. * `min_sequence_len`: Specifies the minimum sequence length of the tokenized doc. Docs having less than `min_sequence_len` will be discarded. * `fraction_of_RAM_alloted`: Upper limit on fraction of RAM allocated for processing. Defaults to 0.7 (70% of available RAM). **Data Handling Params** * `read_chunk_size`: The size of chunks to read from the input data, specified in KB. Defaults to 1024 KB (1 MB). * `write_chunk_size`: The size of chunks to write to the output data, specified in KB. Defaults to 1024 KB (1 MB). * `write_in_batch`: Boolean flag indicating whether to write data in batches. Defaults to `False`. * `shuffle`: Boolean flag indicating whether to shuffle the data. Defaults to `False`. If `True`, the shuffle seed is also set. * `shuffle_seed`: The seed for shuffling data. Defaults to 0 if not specified. * `token_limit`: Stop the data preprocessing pipeline after a specified number of tokens are processed. **Read Hooks Params** * `read_hook`: Path to the read hook function. See an example [here](#example-configuration). Defaults to `None`. User must provide the `read_hook` for every preprocessing run. * `read_hook_kwargs`: A dictionary of keyword arguments for the read hook function. Must include the keys to be used for data processing with the naming convention `*_key`. See an example [here](#example-configuration). **Tokenization Params** * `huggingface_tokenizer`: Parameter to provide Hugging Face tokenizer * `custom_tokenizer`: Parameter to provide custom tokenizer. * `tokenizer_params`: Parameter to provide additional parameters to initialize tokenizer. For more details [check the Initialization](#initialization-process). * `input_ids_dtype`: dtype of processed input\_ids. Defaults to `int32`. * `input_mask_dtype`: dtype of processed input loss masks. Defaults to `int32`. **Text Processing Params** * `use_ftfy`: Boolean flag indicating whether or not to fix text with ftfy. * `ftfy_normalizer`: Choose what kind of unicode normalization is applied. Usually, we apply NFC normalization, so that letters followed by combining characters become single combined characters. Using None applies no normalization while fixing text. Defaults to `NFC`. * `wikitext_detokenize`: Use wikitext detokenizer to fix text. Defaults to `False`. **Sequence Control Params** * `short_seq_prob`: Probability of creating sequences which are shorter than the maximum sequence length. Defaults to `0.0` . **Semantic Masks and Weights Params** * `semantic_drop_mask`: Dictionary which indicates which semantic region to drop from input data before tokenization. Defaults to `{}`. * `semantic_loss_weight`: Dictionary which indicates the loss mask of the different semantic regions post tokenization. Defaults to `{}`. * `semantic_attention_mask`: Dictionary which indicates the attention mask of the different semantic regions. Defaults to `{}`. > [!NOTE] > > The keys provided in the `read_hook_kwargs` flag should end with `*_key`. > > The `max_seq_length` specified in the processing section of the data config should match `max_position_embeddings` in the `model` section in the model’s config. Also make sure the `vocab_size` in the `model` section in the model’s config matches the vocab size of the tokenizer used for data preprocessing. ### Example Processing Section ```yaml theme={null} processing: huggingface_tokenizer: "unsloth/Llama-3.3-70B-Instruct" max_seq_length: 4096 write_in_batch: True resume_from_checkpoint: False read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks:chat_read_hook" read_hook_kwargs: multi_turn_key: "messages" multi_turn_content_key: "content" multi_turn_role_key: "role" shuffle_seed: 0 shuffle: False use_ftfy: True ftfy_normalizer: "NFC" wikitext_detokenize: False token_limit: 1024000 ``` ## Dataset Section The following dataset parameters are also processed: * `use_vsl`: A boolean parameter indicating whether to use VSL (variable sequence length) mode. * `is_multimodal`: A boolean parameter indicating whether the dataset is multimodal. * `training_objective`: Specifies the training objective which can either be `fim` or `mlm`. `mlm` is for masked language modeling which is a part of pretraining token generator. * `truncate_to_msl`: Specifies if truncation of sequences needs to be done, to fit a sequence within the MSL. This is applicable only for `FineTuning` as well as `VSLFineTuning` modes. (For more details, please refer to the section on truncation [here](../model-zoo/components/data-preprocessing/truncation)) > [!NOTE] > > `use_vsl` is not supported for multimodal tasks. ## Read Hook Function A read hook function is a user-defined function that customizes the way data is processed. This function can be specified through a configuration parameter under `processing` section in the config and is crucial for preprocessing datasets. The parameter fields it takes are `read_hook` and `read_hook_kwargs`. > [!WARNING] > > * Always ensure that a read hook function is provided for datasets to handle the data types appropriately. > > * Specify the read hook path in the configuration in the format `module_name:func_name` to ensure the correct function is loaded and utilized. ### Example Configuration Here is how to specify a format hook function in the configuration: ```yaml theme={null} processing: read_hook: "my_module.my_submodule:my_custom_hook" read_hook_kwargs: key1_key: "" key2_key: "" param1: value1 param2: value2 ``` This configuration will load “my\_custom\_hook” from “my\_module.my\_submodule” and bind `data_keys`, `param1`, and `param2` with the respective values. > [!NOTE] > > The user must name key parameter of data related keys with `_key`. For example, the user can name the key for text as `text_key: "text"`. For finetuning it can be names as `prompt_key: "prompt"`. > > This is important because this is how data processing framework identifies data keys in `read_hook_kwargs` from other parameters in the kwargs. An example of finetuning read hook args is shown below. > > ```yaml theme={null} > processing: > read_hook: "my_module.my_submodule:my_custom_hook" > read_hook_kwargs: > prompt_key: "prompt" > completion_key: "completion" > param1: value1 > param2: value2 > > ``` ## Tokenizer Initialization This section describes how the tokenizer is initialized based on the provided processing parameters. The initialization process handles different types of tokenizers, including Hugging Face tokenizer, GPT-2, NeoX, and custom tokenizers. ### Configuration Parameters * `huggingface_tokenizer`: Specifies the Hugging Face tokenizer to use. * `custom_tokenizer`: Specifies the custom tokenizer to use. The way to specify custom tokenizer is same as any other custom module - you can use `module_name:tokenizer_name`. `gpt2tokenizer` and `neoxtokenizer` are provided as special case, custom tokenizers for legacy reasons. For more details about custom tokenizers, refer to - \_custom-tokenizer-section. * `tokenizer_params`: A dictionary of additional parameters for the tokenizer. These parameters are passed to the tokenizer during initialization. * `eos_id`: Optional. Specifies the end-of-sequence token ID. Used if the tokenizer does not have an `eos_id`. * `pad_id`: Optional. Specifies the padding token ID. Used if the tokenizer does not have a `pad_id`. ### Initialization Process 1. **Handling Tokenizer Types**: * **Hugging Face Tokenizer**: Initialized using AutoTokenizer from Hugging Face. * **Custom Tokenizer**: For custom tokenizers, initialized from the user-provided module and class. 2. **GPT-2 and NeoX Tokenizers**: * Kept as custom tokenizers because they require custom `vocab` and `encoder` files for initialization which are located in ModelZoo. Note that you can still use Hugging Face tokenizers for GPT2 and NeoX. But, these tokenizers exist for legacy reasons. 3. **Override IDs**:For GPT-2 tokenizers, make sure the `pad_id` is set to the same value as the `eos_id`. * Override the `eos_id` and `pad_id` if specified in the processing parameters. Ensure that the `eos_id` and `pad_id` provided in the configuration match the tokenizer’s `eos_id` and `pad_id`, if available. ### Example Configurations #### Hugging Face Tokenizer ```yaml theme={null} processing: huggingface_tokenizer: "bert-base-uncased" tokenizer_params: param1: value1 param2: value2 ``` This configuration will initialize the specified Hugging Face tokenizer with specific parameters. #### GPT-2 Tokenizer GPT-2 and NeoX tokenizers are treated as custom tokenizers because they require specific `vocab` and `encoder` files for initialization. These files must be provided through the `tokenizer_params`. ```yaml theme={null} processing: custom_tokenizer: "gpt2tokenizer" tokenizer_params: vocab_file: "path/to/vocab.json" encoder_file: "path/to/merges.txt" ``` #### NeoX Tokenizer ```yaml theme={null} processing: custom_tokenizer: "neoxtokenizer" tokenizer_params: encoder_file: "path/to/encoder.json" ``` #### Custom Tokenizer ```yaml theme={null} processing: custom_tokenizer: "path.to.module:tokenizer_class" tokenizer_params: param1: "param1" param2: "param2" ``` ## Output Files Structure The output directory will contain a number of `.h5` files as shown below: ```bash theme={null} ├── checkpoint_process_0.txt ├── checkpoint_process_1.txt ├── data_params.json ├── output_chunk_0_0_0_0.h5 ├── output_chunk_1_0_0_0.h5 ├── output_chunk_1_0_16_1.h5 ├── output_chunk_0_0_28_1.h5 ├── output_chunk_0_0_51_2.h5 ├── output_chunk_1_0_22_2.h5 ├── output_chunk_0_1_0_3.h5 ├── ... ``` * `data_params.json` stores the parameters used for generating this set of files. * `checkpoint_*.txt` can be used for resuming the processing in case the run script gets killed for some reason. To use this file, simply set the `resume_from_checkpoint` flag to `True` in the processing section inside the configuration file. ## Statistics Generated After Preprocessing After preprocessing has been completed, the following statistics are generated in `data_params.json`: | Attribute | Description | | - | - | | `average_bytes_per_sequence` | The average number of bytes per sequence after processing | | `average_chars_per_sequence` | The average number of characters per sequence after processing | | `discarded_files` | The number of files discarded during processing because the resulting number of token IDs were either greater than the MSL or less than the `min_sequence_len` | | `eos_id` | The token ID used to signify the end of a sequence | | `loss_valid_tokens` | Number of tokens on which loss is computed | | `n_examples` | The total number of examples (sequences) that were processed | | `non_pad_tokens` | Non pad tokens | | `normalized_bytes_count` | The total number of bytes after normalization (e.g., UTF-8 encoding) | | `normalized_chars_count` | The total number of characters after normalization (e.g., lowercasing, removing special characters) | | `num_masked_tokens` | The total number of tokens that were masked (used in tasks like masked language modeling) | | `num_pad_tokens` | The total number of padding tokens used to equalize the length of the sequences | | `num_tokens` | Total number of tokens | | `pad_id` | The token ID used as padding | | `processed_files` | The number of files successfully processed after tokenizing | | `raw_bytes_count` | The total number of bytes before any processing | | `raw_chars_count` | The total number of characters before any processing | | `successful_files` | The number of files that were successfully processed without any issues | | `total_raw_docs` | The total number of raw docs present in the input data | | `raw_docs_skipped` | The number of raw docs that were skipped due to missing sections in the data | | `vocab_size` | The size of the vocabulary used in the tokenizer | ## What’s Next? Now that you’ve mastered the essentials of data preprocessing on Cerebras Systems, dive deeper into configuring your input data with our detailed guide on [Input Data Configuration](./input-data-configuration) on Cerebras Systems. This guide will help you set up and manage local and Hugging Face data sources effectively, ensuring seamless integration into your preprocessing workflow. Additionally, explore the various [read hooks](./read-hooks) available for data processing. These read hooks are tailored to handle different types of input data, preparing it for specific machine learning tasks. Understanding and utilizing these read hooks will further enhance your data preprocessing capabilities, leading to better model performance and more accurate results. # Configure Input Data Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/data-preprocessing/input-data-configuration Learn how to configure your input data for preprocessing—whether you're working with a single directory of data or organizing large datasets into subsets. You can configure **local** or **Hugging Face** data as input for preprocessing. In this guide you'll learn how to define your data source, specify optional parameters like subsets or splits, and structure your config file to support flexible, scalable preprocessing workflows. ## Local Data * Set `type` to `local`. * Use `source` to provide the path to the input directory. For example: ```yaml theme={null} setup: data: source: "/input/dir/here" type: "local" mode: "pretraining" output_dir: "./output/dir/here/" processes: 1 ``` ### Preprocess Subdirectories You can optionally preprocess subdirectories within your input directory as **separate datasets**. This enables more flexible data management for large-scale pretraining tasks. There are two supported options: * Use `top_level_as_subsets: True` to automatically treat **each top-level folder** in your input directory as a separate dataset. Each top-level directory is treated as a subset and a separate output folder will be created under `output_dir` with its respective preprocessed HDF5 files. Defaults to `False` if not specified. * Use `subsets: [list]` to manually specify which subfolders to preprocess. Only the folders listed in subsets will be preprocessed and each subset will have its own output folder under `output_dir`. Use the tabs to view examples: ```yaml Top-Level Subsets {5} theme={null} setup: data: source: "input_dir" type: "local" top_level_as_subsets: True mode: "pretraining" output_dir: "./output_dir" processes: 1 ``` ```yaml Specific Subfolders {5} theme={null} setup: data: source: "input_dir" type: "local" subsets: ["subset_1", "subset_2" ...] mode: "pretraining" output_dir: "./output_dir" processes: 1 ``` ## Hugging Face Data * Set `type` to `huggingface`. * Use `source` to specify the dataset name from the Hugging Face hub. * Use `split` to specify the dataset split. The preprocessing pipeline passes these parameters to the Hugging Face `load_dataset` API. > [!NOTE] > > When calling the API, parameters are passed as keyword arguments and they must conform to the specifications outlined by HuggingFace. Refer to the `load_dataset` documentation [here](https://huggingface.co/docs/datasets/v2.20.0/en/package_reference/loading_methods#datasets.load_dataset). For example: ```yaml Hugging Face Data {3-5} theme={null} setup: data: source: "stanfordnlp/imdb" type: "huggingface" split: "test" cache_dir: "path/to/cache_dir" ...other parameters accepted by HuggingFace ``load_dataset`` API... mode: "pretraining" output_dir: "./output/dir/here/" processes: 1 ``` > [!TIP] > > View example configs for various use cases [here](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/data_preparation/data_preprocessing/configs). # On-The-Fly Data Processing Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/data-preprocessing/on-the-fly-data-processing Learn how to enable on-the-fly (OTF) data preprocessing during training and/or evaluation. The preprocessing section in the `train_input` and `eval_input` sections of the YAML configuration file enables on-the-fly data preprocessing during training and/or evaluation, which reduces turnaround time and storage requirements when running experiments on smaller datasets. The parameters for preprocessing are the same as those used for offline data preprocessing, applying the same algorithms and techniques. For multibox runs, sharding is based on the number of input files in the input directory, which should be greater than or equal to the product of the number of systems and workers per system. Below are examples for pretraining and fine-tuning configurations. We currently support OTF preprocessing for pretraining and finetuning on text-only and multimodal datasets. ## Example Text-Only Configurations Use the tabs to view examples for text-only pretraining and finetuning: ```yaml Pretraining theme={null} train_input: preprocessing: data_processor: "RawDatasetProcessor" processing: custom_tokenizer: gpt2tokenizer tokenizer_params: encoder_file: /path/to/gpt2-encoder.json vocab_file: /path/to/gpt2-vocab.bpe sep_token: None batch_size: 4 max_seq_length: 256 seed: 0 read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks:text_read_hook" read_hook_kwargs: text_key: "text" dataset: pack_sequences: True use_vsl: False setup: data: source: /path/to/text_data type: local mode: pretraining processes: 1 ``` ```yaml Finetuning theme={null} train_input: preprocessing: processing: data_processor: "RawDatasetProcessor" custom_tokenizer: gpt2tokenizer tokenizer_params: encoder_file: /path/to/gpt2-encoder.json vocab_file: /path/to/gpt2-vocab.bpe batch_size: 4 max_seq_length: 2048 seed: 0 read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks:prompt_completion_text_read_hook" read_hook_kwargs: prompt_key: "prompt" completion_key: "completion" dataset: sep_token: null setup: data: source: /path/to/sum_data type: local mode: finetuning processes: 1 ``` ## Multimodal Example Configurations Use the tabs to view examples for multimodal pretraining and finetuning: ```yaml Multimodal Pretraining theme={null} train_input: preprocessing: data_processor: "MultimodalRawDatasetProcessor" processing: custom_tokenizer: gpt2tokenizer tokenizer_params: encoder_file: /path/to/gpt2-encoder.json vocab_file: /path/to/gpt2-vocab.bpe batch_size: 4 max_seq_length: 256 seed: 0 read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks:pretraining_image_captions_hook" read_hook_kwargs: image_key: "image" caption_key: "caption" dataset: image_dir : /path/to/image_files is_multimodal: True setup: data: source: /path/to/text_data type: local mode: pretraining processes: 1 ``` ```yaml Multimodal Finetuning theme={null} train_input: preprocessing: processing: data_processor: "MultimodalRawDatasetProcessor" custom_tokenizer: gpt2tokenizer tokenizer_params: encoder_file: /path/to/gpt2-encoder.json vocab_file: /path/to/gpt2-vocab.bpe batch_size: 4 max_seq_length: 2048 seed: 0 read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks:finetuning_llava_hook" read_hook_kwargs: multi_turn_key: "conversation" image_key: "image_path" image_token: "" multi_turn_role_key: "role" multi_turn_content_key: "value" phase: 2 dataset: image_dir : /path/to/image_files is_multimodal: True sep_token: null setup: data: source: /path/to/text_data type: local mode: finetuning processes: 1 ``` > [!NOTE] > > We don't support global shuffling with on-the-fly processing. This feature will be released in subsequent releases. # Read Hooks Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/data-preprocessing/read-hooks This guide details various read hooks you can use to convert different types of raw input data into HDF5 format for machine learning tasks on Cerebras Systems. ## What is a Read Hook? We use read hooks to convert from different input formats to HDF5 format. Pre-built hooks are provided for standard input formats and masking schemes. ![](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/data_preproc_diagram.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=43f91f79ed639c34c05d557bb4f79b50) Our end-to-end data processing pipeline, pictured above, consists of three stages: **1. Read** Data is sourced from either a local file store or the Hugging Face Hub and processed by the Reader module, which applies a `read_hook` before converting the data into a `SemanticDataArray`. **2. Tokenize** The data is then transformed using one of three token generators—pre-training, fine-tuning, or custom—depending on the use case. **3. Write** The processed tokens undergo internal processing via the Writer module and are stored in HDF5 format, forming the `TokenFlow`. This structured approach ensures efficient handling and tokenization of input data for downstream tasks. This guide explores how to configure and utilize pre-built read hooks to streamline data preprocessing across different data types and platforms, enabling more robust and adaptable machine learning pipelines. By mastering read hooks, you'll gain the ability to: * Seamlessly integrate local and HuggingFace data sources * Customize data loading for specific tasks * Optimize preprocessing efficiency * Enhance overall model performance > [!TIP] > > See [Write a Custom Read Hook](../../../model-zoo/components/data-preprocessing/semantic-regions) to learn how to create your own. ## Fine-tuning LLaVA Hook This read hook processes conversation data to format it for fine-tuning LLaVA models. It looks for conversation turns, optional system prompts, and images. It requires keys for conversation data and image paths. ```yaml Config Example theme={null} read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks.finetuning_llava_hook" read_hook_kwargs: multi_turn_key: "conversation" image_key: "image_path" image_token: "" multi_turn_role_key: "from" multi_turn_content_key: "value" phase: 2 ``` ```yaml Return Structure theme={null} [ { "type": "system", "content": [{"text": "A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions."}] }, { "type": "user", "content": [ {"image": "path/to/image.jpg"}, {"text": "User's text before and after image"} ], "semantic_drop_mask": [False, False] }, { "type": "assistant", "content": [{"text": "Assistant's response"}], "semantic_drop_mask": [False] } ] ``` ## Pretraining Text Hook This read hook extracts and processes plain text data for reading tasks. It requires a key to extract text from input data. ```yaml Config Example theme={null} read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks.text_read_hook" read_hook_kwargs: text_key: "text" ``` ```yaml Return Structure theme={null} [ { "content": [ {"text": "Extracted text data"} ] } ] ``` ## Pretraining Image Captions Hook This read hook prepares data for image captioning pretraining tasks by extracting image paths and captions. ```yaml Config Example theme={null} read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks.pretraining_image_captions_hook" read_hook_kwargs: image_key: "image" caption_key: "caption" ``` ```yaml Return Structure theme={null} [ { "content": [ {"image": "Path to the image"}, {"text": "Caption describing the image"} ] } ] ``` ## NLG Hook This read hook processes natural language generation (NLG) data, organizing context and completion information into a structured format. It requires context and completion keys. ```yaml Config Example theme={null} read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks.nlg_read_hook" read_hook_kwargs: context_key: "context" completion_key: "completion" ``` ```yaml Return Structure theme={null} [ { "type": "context", "content": [ {"text": "Context of the conversation"} ] }, { "type": "completion", "content": [ {"text": "Generated response"} ] } ] ``` ## Prompt Completion Text Hook This read hook formats prompt and completion text into a structured list. It requires prompt and completion keys. ```yaml Config Example theme={null} read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks.prompt_completion_text_read_hook" read_hook_kwargs: prompt_key: "prompt" completion_key: "completion" ``` ```yaml Return Structure theme={null} [ { "type": "prompt", "content": [ {"text": "Prompt text"} ] }, { "type": "completion", "content": [ {"text": "Completion text"} ] } ] ``` ## Chat Hook This read hook transforms chat data into a semantic data array, distinguishing between user and assistant roles. Assumes data is in conversation format and requires a key for multi-turn content if the data is not in OpenAI ChatML format. ```yaml Config Example theme={null} read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks.chat_read_hook" read_hook_kwargs: multi_turn_key: "messages" multi_turn_role_key: "role" multi_turn_content_key: "content" ``` ```yaml Return Structure theme={null} [ {"type": "user", "content": [{"text": "User message"}]}, {"type": "assistant", "content": [{"text": "Assistant message"}]} ] ``` ## DPO Hook This read hook structures data for Direct Preference Optimization (DPO) tasks, organizing prompts, chosen responses, and rejected responses into semantic data array. Requires keys for prompt, chosen, and rejected data. The implementation can be found [here](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//data_preparation/data_preprocessing/hooks.py#L331). ```yaml Config Example theme={null} read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks.dpo_read_hook" read_hook_kwargs: prompt_key: "prompt" chosen_key: "chosen" rejected_key: "rejected" assistant_role: "assistant:" ``` ```yaml Return Structure theme={null} [ {"type": "prompt", "content": [{"text": "Prompt text"}]}, {"type": "chosen", "content": [{"text": "Chosen response"}]}, {"type": "rejected", "content": [{"text": "Rejected response"}]} ] ``` ## Prompt Completion Chat Hook This read hook processes prompt and completion data as a single turn chat and creates a semantic data array format. The implementation can be found [here](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//data_preparation/data_preprocessing/hooks.py#L433). ```yaml Config Example theme={null} read_hook: "cerebras.modelzoo.data\_preparation.data\_preprocessing.hooks.prompt\_completion\_chat\_read\_hook" read\_hook\_kwargs: prompt_key: "prompt" completion_key: "completion" ``` ```yaml Return Structure theme={null} [ { "type": "user", "content": [ {"text": "User's prompt text"} ] }, { "type": "assistant", "content": [ {"text": "Assistant's completion text"} ] } ] ``` ## Fine-Tuning Image Captions Hook Processes fine-tuning image captions data into a semantic data array format. Requires keys for image and caption data. The hook implementation can be found [here](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//data_preparation/data_preprocessing/hooks.py#L473). ```yaml Config Example theme={null} read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks.finetuning_image_captions_hook" read_hook_kwargs: image_key: "image" caption_key: "caption" ``` ```yaml Return Structure theme={null} [ { "type": "prompt", "content": [ {"image": "Path to the image"} ] }, { "type": "completion", "content": [ {"text": "Caption describing the image"} ] } ] ``` ## Fine-Tuning LLaVA Hook Prompt Completion This read hook transforms conversation data for fine-tuning LLaVA, alternating between prompt and completion roles. Requires keys for conversation data and image paths. The hook implementation can be found [here](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//data_preparation/data_preprocessing/hooks.py#L530). ```yaml Config Example theme={null} read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks.finetuning_llava_hook_prompt_completion" read_hook_kwargs: multi_turn_key: "conversation" multi_turn_role_key: "role" multi_turn_content_key: "content" image_key: "image_path" image_token: "" phase: 1 ``` ```yaml Return Structure theme={null} [ { "type": "system", "content": [{"text": "A chat between a curious human and an artificial intelligence " "assistant. The assistant gives helpful, detailed, and polite answers " "to the human's questions."}] }, { "type": "prompt", "content": [ {"image": "path/to/image.jpg"}, {"text": "User's text before and after image"} ], "semantic_drop_mask": [False, True] }, { "type": "completion", "content": [{"text": "Assistant's response"}], "semantic_drop_mask": [False] } ] ``` ## Important Considerations * **Handling keys to read data**: The `read_hook_kwargs` property must have data keys with the suffix `_key` to segregate these from other parameters for `read_hook_kwargs`. These keys will be exclusively used to read data from the input while other parameters which are not data keys will be used to create semantic data array from the read hooks. * **Space Handling**: When combining custom regions, the data processor does not add any spaces or separators between the regions. Space handling must be managed within the read hooks. When creating custom semantic regions, ensure there is a leading space at the start of each region (except the first) to prevent the merging of words from neighboring regions. * **Multimodal Datasets**: When working with multimodal datasets, if images are provided as URLs, the hooks should download the images and generate image paths to be used by the multimodal models. * **Separator Handling With Prompt Completion Read Hook**: The token generator adds a separator token between `prompt` and `completion` semantic regions. The tokenizer’s `sep_token` attribute is used as a separator token if present; else we use `<|sep|>`. ## What’s Next? Now that you’ve configured your input data and understand how to process it using various read hooks, the next step is to set up your [token generators](../../../model-zoo/components/data-preprocessing/token-generators). Token generators play a crucial role in the preprocessing pipeline, as they convert raw data into tokenized formats suitable for machine learning models. # Write a Custom Read Hook Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/data-preprocessing/semantic-regions Learn how to create custom read hooks for processing different data formats into semantic data arrays, enabling flexible data preprocessing for AI model training. Read hooks are essential components for processing training data into a standardized format for AI models. They convert various input formats into semantic data arrays, which organize content into meaningful regions with specific attributes like loss masking and attention control. This guide will show you how to write custom read hooks by understanding semantic regions and the semantic data array structure. > [!TIP] > > Learn more about pre-built read hooks [here](../../../model-zoo/components/data-preprocessing/read-hooks). ## What is a Semantic Region? To write effective read hooks, you first need to understand semantic regions. A semantic region is a section of data that shares a common meaning. This concept is particularly important for instruction-following datasets where different parts of the input serve different purposes. For example, in a dialogue dataset, user questions and assistant responses are distinct semantic regions that need different treatment during training. Traditional approaches often use rigid, hard-coded masking for these sections, but semantic regions provide more flexibility. ## Why Use Semantic Regions? Let's consider the user and assistant sections of a dialogue as two special cases of a semantic region. The user section shows the model an example question, which is distinct from the assistant response that demonstrates the desired output of the model. For pedagogical purposes, we introduce a simple representation to visualize semantic regions. Below, the tuple contains `(text, loss_mask_value)`: ```python theme={null} [ ("Hello how are you doing?", 0), ("I'm great, how are you?", 1) ] ``` The above case fits easily into existing frameworks. However, consider a medical question-answering dataset with three key components: * A medical passage * A related question * An answer In older, hard-coded systems, you would have to: 1. Combine the passage and question into a single "user" region 2. Lose the ability to learn from the medical passage during training Our semantic regions approach solves this by allowing granular separation: ```python theme={null} [ ("The patient's TSH levels are elevated due to hypothyroidism", 1), ("What is the relation between TSH and hypothyroidism?", 0), ("Hypothyroidism is associated with elevated TSH levels", 1) ] ``` Similarly, consider the case where we have question-answering on Confluence documents. There are 'structure tokens' that represent section headers and metadata (Date, Author, or Last Updated) that are not useful to learn to predict. We can separate out structure tokens into semantic regions that get loss-masked, but include loss over the useful content in the user section: ```python theme={null} [ ("Date: 2024-05-06", 0), ("Author: jquxizop", 0), ("This feature improves performance by 3x.", 1), ("Viewed by: 1,520", 0), ("How does the feature work?", 0), ("The features works by...", 1) ] ``` > [!NOTE] > > We currently do not offer the ability to divide inputs into different semantic regions in `pretraining` mode. We offer this capability in finetuning mode, for both text and multi-modal datasets. ## Semantic Data Arrays We also introduce a data specification for our processing pipeline, called the *semantic data array*. Input data can come in a variety of formats, but we require a standard format to correctly parse it into semantic regions so that we can apply the corresponding attributes such as loss weight. ```python theme={null} [ { "type": "...", "content": [...], "semantic_loss_weight" (Optional): [...], "semantic_drop_mask" (Optional): [...], "semantic_attention_mask" (Optional) [...] }, ... { "type": "...", "content": [...], "semantic_loss_weight" (Optional): [...], "semantic_drop_mask" (Optional): [...], "semantic_attention_mask" (Optional) [...] }, ] ``` The `type` field controls behavior for chat templates (more details [here](https://huggingface.co/docs/transformers/v4.35.1/en/chat_templating)), and can take values of `"system", "prompt", "completion", "user", "assistant"`. The difference between prompt/completion and user/asssistant is whether we apply a chat-template: prompt/completion *does not* apply the template, and user/assistant *does* apply the chat template. The `content` field is a list of dictionaries, where the key is the name of the semantic region, and the value is the content of the semantic. Currently, the `image` semantic region is special and the content would have to be a string that represents the path to the image. Other regions names besides `image` will be interpreted as text. The `semantic_loss_weight` and `semantic_{drop/attention}_mask` are optional, and have default values according to the `type` field. If specified, they should be a list that has the *same number of entries* as the content list. By default, `completion` and `assistant` are not loss-masked, i.e. have `semantic_loss_weight = 1`. The `system`, `prompt`, and `user` types have default of `semantic_loss_weight = 0`. All types have default of `semantic_attention_mask = 1`, i.e. they have attention paid to them. All types also have defaults of `semantic_drop_mask = False`, which means they are not dropped. The popular LLaVA model dropped the text from their prompts in one phase of training, so we introduced this feature to support the ability to drop arbitrary semantic regions according to a desired scheme (more details [here](https://arxiv.org/abs/2304.08485)). Now let us represent some of the pedagogical examples from above into real semantic data arrays: ```python theme={null} [ { "type": "user", "content": [ {"passage": "The patient's TSH levels are elevated due to hypothyroidism"}, {"question": " What is the relation between TSH and hypothyroidism?"} ], "semantic_loss_weight": [1, 0] }, { "type": "assistant", "content": [ {"text": "Hypothyroidism is associated with elevated TSH levels"} ], "semantic_loss_weight": [1] }, ] ``` > [!NOTE] > > When creating custom semantic regions, ensure there is a leading space at the start of each region (except the first) to prevent the merging of words from neighboring regions. ## Read Hooks to Organize Semantic Data Arrays We use read hooks to convert from different input formats to our semantic data array. Pre-built hooks are provided for standard input formats and masking schemes, but the hooks also allow you to write code to transform arbitrary inputs into any valid configuration of the semantic data array. ![](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/data_preproc_diagram.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=43f91f79ed639c34c05d557bb4f79b50) ```python theme={null} [ { "type": "prompt", "content": [ {"image": "path/to/image.jpg"}, {"text": "User's text before and after image"} ], "semantic_drop_mask": [False, True], "semantic_attention_mask": [True, False], "semantic_loss_weight": [0, 1], }, { "type": "completion", "content": [{"text": "Assistant's response"}], "semantic_drop_mask": [False], "semantic_attention_mask": [True], "semantic_loss_weight": [1], } ] ``` In this example, the drop mask is set to `True` for the text region of "prompt," indicating that this text portion will be dropped from the dataset and not tokenized. The semantic attention mask determines which regions contribute to the final attention mask passed to the model. A loss weight of 0 for a region means that the label tokens corresponding to that region will not be included in the loss calculation. > [!NOTE] > > The value of the semantic loss weight should be either 0 or 1. ## Custom Read Hook Examples This section describes examples of custom read hooks for processing data on Cerebras Systems. The return data fields are: **1. type** Indicates the role in the conversation. Possible values are system, user, assistant, prompt, or completion. **2. content** A list of dictionaries representing parts of the conversation turn. Each dictionary can contain: * text: A segment of text. * image: The path to an image (if applicable). **3. semantic\_loss\_weight** A list of booleans indicating which parts of the content might be dropped during training for semantic purposes. ### Ultra Chat Common Words Mask Hook This hook masks selected words in the sequence and was written for Ultrachat data. The link to the dataset is [here](https://huggingface.co/datasets/HuggingFaceH4/ultrachat_200k). The hook implementation can be found [here](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//data_preparation/data_preprocessing/custom_hook_examples/custom_hooks.py#L144). ```yaml Config Example theme={null} read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks.ultra_chat_common_words_mask_hook" read_hook_kwargs: prompt_key: "prompt" completion_key: "completion" ``` ```yaml Return Structure theme={null} [ { "type": "prompt", "content": [{"text": "Prompt text"}] }, { "type": "completion", "content": [{"text": chunk} for chunk in completion_chunks], "semantic_loss_weight": completion_loss_mask } ] ``` ### Obelics Hook Processes obelics dataset examples into a semantic data array format. Requires keys for image and text data. The dataset link and description can be found [here](https://huggingface.co/datasets/HuggingFaceM4/OBELICS). The hooks implementation can be found [here](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//data_preparation/data_preprocessing/custom_hook_examples/custom_hooks.py#L58). ```yaml Config Example theme={null} read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks.obelics_hook" read_hook_kwargs: image_key: "image_urls" caption_key: "captions" image_dir: "/path/to/image_dir" ``` ```yaml Return Structure theme={null} [ { "content": [ {"text": "Text caption"}, {"image": "unique_image_name.png"} ] } ] ``` ### Llama3.1 Chat Template Formatted Data Hook Processes a multi turn conversation dataset on which chat template of the tokenizer `meta-llama/Meta-Llama-3-8B-Instruct` has already been applied, into a semantic data array format. Requires keys for image and text data. The dataset link and description for a sample dataset can be found [here](https://huggingface.co/datasets/sumandas/openhermes-2.5-llama3). The hooks implementation can be found [here](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//data_preparation/data_preprocessing/custom_hook_examples/custom_hooks.py#L58). ```yaml Config Example theme={null} read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks.llama3_1_chat_formatted_data_hook" read_hook_kwargs: chat_key: "text" ``` ```yaml Return Structure theme={null} [ {"type": "system", "content": [{"text": "System message"}]}, {"type": "user", "content": [{"text": "User message"}]}, {"type": "assistant", "content": [{"text": "Assistant message"}]} ] ``` ## Important Considerations * **Handling keys to read data**: The `read_hook_kwargs` property must have data keys with the suffix `_key` to segregate these from other parameters for `read_hook_kwargs`. These keys will be exclusively used to read data from the input while other parameters which are not data keys will be used to create semantic data array from the read hooks. * **Space Handling**: When combining custom regions, the data processor does not add any spaces or separators between the regions. Space handling must be managed within the read hooks. When creating custom semantic regions, ensure there is a leading space at the start of each region (except the first) to prevent the merging of words from neighboring regions. * **Multimodal Datasets**: When working with multimodal datasets, if images are provided as URLs, the hooks should download the images and generate image paths to be used by the multimodal models. * **Separator Handling With Prompt Completion Read Hook**: The token generator adds a separator token between `prompt` and `completion` semantic regions. The tokenizer’s `sep_token` attribute is used as a separator token if present; else we use `<|sep|>`. # Token Generators Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/data-preprocessing/token-generators Learn about supported Token Generators for data preprocessing. Token generators convert raw data into tokenized formats suitable for machine learning models, ensuring efficient and effective data processing. This guide covers the configuration of pre-built and custom token generators, along with examples and use cases. ## Pre-Built Token Generators Cerebras Model Zoo provides a comprehensive suite of pre-built token generators tailored to support various stages and tasks in the development of LLMs. The initialization of these token generators is dependent on the `mode` parameter that is specified in the config file (refer to [Modes](../../../model-zoo/components/data-preprocessing/data-preprocessing#modes). ### Flags Supported by Pre-Built Token Generators > [accordion] Pretraining Parameters > > This section lists parameters that can be used for `PretrainingTokenGenerator`. > > | Flag | Default Value | Description | > | - | - | - | > | pack\_sequences | True | Concatenate a document smaller than maximum sequence length with other documents, instead of filling it with Padding token. | > | inverted\_mask | False | If False, 0 represents masked positions. If True 1 represents masked positions. | > | seed | 0 | Random seed used for generating short sequences | > | short\_seq\_prob | 0.0 | Probability of creating sequences which are shorter than the maximum sequence length. | > | split\_text\_to\_tokenize | False | Whether to split the text into smaller chunks before tokenization. This is helpful for very long documents with tokenizers such as Llama tokenizer which performs quadratically in the text length. | > | chunk\_len\_to\_split | 2000 | Length of the text chunks to split the text into before tokenization for slower tokenizers. Could be optionally used with the above flag split\_text\_to\_tokenize. Without the previous flag, this argument will be ignored. | > | remove\_bos\_in\_chunks | False | Whether to remove the BOS token from the beginning of the chunks. Set this to True when using split\_test\_to\_tokenize and chunk\_len\_to\_split to avoid having multiple BOS tokens in the middle of the text. Not applicable to all tokenizers. | > > > [!NOTE] > > > > In this case, it also uses all the config paramaters that are used by `PretrainingTokenGenerator`, in addition to the ones specified below. > > | Flag | Default Value | Description | > | - | - | - | > | mlm\_fraction | 0.15 | Fraction of tokens to be masked in MLM tasks. | > | mlm\_with\_gather | False | MLM processing mode. When set to True the length of the returned labels is equal to mlm\_fraction \* msl, else it is equal to msl | > | ignore\_index | -100 | Required when mlm\_with\_gather is set to False. Presence of ignore\_index value at a position in the labels indicates that this position will not be used for loss calculation. | > | excluded\_tokens | \[‘\’, ‘\’, ‘\’, ‘\’, ‘\’, ‘\’] | Tokens to be excluded when masking. Provided only through YAML config. | > [accordion] VSL Finetuning Token Generator Parameters > > This section lists down parameters that can be used for `VSLFineTuningTokenGenerator`. > > > [!NOTE] > > > > `VSLFineTuningTokenGenerator` also uses the config paramaters that are used by `FineTuningTokenGenerator`, in addition to the ones specified below. > > | Flag | Default Value | Description | > | - | - | - | > | use\_vsl | True | Generate examples with multiple sequences packed together | > | position\_ids\_dtype | int32 | dtype of token position ids. | > > > [!NOTE] > > > > Note > > > > Increasing the read chunk size will increase the packing factor of VSL. So, the user needs to figure out the tradeoff between higher packing and processing time depending on the dataset’s packing factor. > [accordion] VSL Pretraining Token Generator Parameters > > This section lists down parameters that can be used for `VSLPretrainingTokenGenerator`. `use_vsl` needs to be set to True in the `train_input` or `eval_input` section of the model config. > > > [!NOTE] > > > > `VSLPretrainingTokenGenerator` also uses the config paramaters that are used by `PretrainingTokenGenerator`, in addition to the ones specified below. > > | Flag | Default Value | Description | > | - | - | - | > | use\_vsl | True | Generate examples with multiple sequences packed together | > | fold\_long\_doc | True | Fold documents larger than max\_seq\_length into multiple sequences, instead of dropping them. | > [accordion] DPO Token Generator Parameters > > This section lists down parameters that can be used for `DPOTokenGenerator`. > > | Flag | Default Value | Description | > | - | - | - | > | max\_prompt\_length | 512 | If the sequence exceeds the `max_seq_length`, this parameters caps the prompt length to the specified limit. | > | response\_delimiter | `` | This is used to set the separator between `prompt` and `response`. The user need not set this value for general use-case. | > [accordion] Multimodal Pretraining Token Generator Parameters > > This section lists down parameters that can be used for `MultiModalPretrainingTokenGenerator`. > > | Flag | Default Value | Description | > | - | - | - | > | max\_num\_img | 1 | Maximum number of images allowed in one preprocessed sequence. Sequences with more than max\_num\_img images will be discarded | > | num\_patches | None | Number of patches to represent an image. This is determined by the patch-size (in pixels) of the image-encoder, and the pixel count of the input images. | > | is\_multimodal | False | Whether the dataset is multimodal (text plus images) or text only. Set it to True for multimodal tasks. | > [accordion] Multimodal Token Generator Parameters > > This section lists down parameters that can be used for multimodal token generators. > > | Flag | Default Value | Description | > | - | - | - | > | max\_num\_img | 1 | Maximum number of images allowed in one preprocessed sequence. Sequences with more than max\_num\_img images will be discarded | > | num\_patches | 1 | Number of patches to represent an image. This is determined by the patch-size (in pixels) of the image-encoder, and the pixel count of the input images. | > | is\_multimodal | False | Whether the dataset is multimodal (text plus images) or text only. Set it to True for multimodal tasks. | ## Supported Token Generators - Pretraining Mode * `PretrainingTokenGenerator`: General-purpose pretraining on large text corpora. When `training_objective` is set to `mlm`, it does MLM task processing. For multimodal pretraining, `is_multimodal` is set to True. * `FIMTokenGenerator`: Designed for fill-in-the-middle tasks. Initialized when `training_objective` is set to `fim` in the config file. * `VSLPretrainingTokenGenerator`: For visual and language pretraining. Initialized when `use_vsl` is set to `True` in the config file. ## Supported Token Generators - Finetuning Mode * `FinetuningTokenGenerator`: General-purpose fine-tuning. For multimodal finetuning, `is_multimodal` is set to True. * `VSLFinetuningTokenGenerator`: Fine-tuning for visual and language tasks. Initialized when `use_vsl` is set to `True` in the config file. ## Other Supported Token Generators * `DPOTokenGenerator`: Focused on direct preference optimization (DPO) during token generation. Initialized when `mode` is set to `dpo`. * `NLGTokenGenerator`: Optimized for natural language generation tasks. Initialized when `mode` is set to `nlg`. ## Custom Token Generators In addition to pre-built token generators, the Model Zoo allows users to implement custom token generators. This enables arbitrary transformations of the input data before tokenization. To use custom token generators, ensure the configuration file is properly set up. Follow these steps: **1.** Ensure that the `mode` param is set to `custom`, in order to be able to specify your own token generator. **2.** Specify the path to the custom token generator class in the config file, in the `token_generator` param, within the `setup` section. This would look like: ``` mode: "custom" token_generator: "" ``` > [!NOTE] > > The `token_generator` path should be specified with the class name being separated with a colon **:** from the module name, for the custom token generator be instantiated correctly. ### Class Implementation Guidelines The custom token generator must adhere to the following guidelines: **1.** The constructor’s signature must be as follows: ```python theme={null} def __init__( self, params: Dict[str, Any], tokenizer: Any, eos_id: int, pad_id: int ): """ Args: params (Dict[str, Any]): Parameters for the dataset and processing. tokenizer (Any): Tokenizer to use for tokenization. eos_id (int): End-of-sequence token ID. pad_id (int): Padding token ID. """ ``` **2.** The custom token generator must implement an `encode` method, which tokenizes and encodes the data according to the user definition. For more examples on how the `encode` method looks like, refer to the code of pre-built token generators that are present in Model Zoo. **3.** The signature of the `encode` method is given below, where it takes in a `semantic_data_array`: ```python theme={null} def encode( self, semantic_data_array: List[Dict[str, Any]] ) -> Tuple[Dict[str, Any], Dict[str, int]]: ``` ## Conclusion Configuring token generators is an important step in the preprocessing pipeline for machine learning tasks on Cerebras Systems. By leveraging the comprehensive suite of pre-built token generators provided by Cerebras ModelZoo, you can efficiently handle various stages and tasks in the development of large language models. Additionally, the flexibility to implement custom token generators allows for tailored transformations of input data, meeting specific project requirements. The introduction of **on-the-fly** data processing further enhances the preprocessing workflow by reducing storage needs and increasing adaptability during training and evaluation. The examples provided for pretraining and fine-tuning configurations illustrate how to set up these processes seamlessly. Finally, the **TokenFlow** utility offers an invaluable tool for visualizing and debugging preprocessed data, ensuring data integrity and facilitating error detection. By following the guidelines and leveraging the tools outlined in this guide, you can optimize your preprocessing pipeline, leading to more efficient training and improved performance of your machine learning models on Cerebras Systems. # Visualization and Debugging Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/data-preprocessing/visualization-and-debugging Learn how to use our TokenFlow tool to visualize and debug your preprocessed data. This tool visualizes preprocessed data efficiently and in an organized fashion, allowing for easy debugging and error-catching of the output data. It can handle both text-only and multimodal datasets, visualizing images if available to verify dataset integrity. TokenFlow supports datasets processed in the following modes - `pretraining`, `finetuning`, `pretraining` with `mlm` and `dpo`. ![](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/getting-started/tokenflow_updated.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=8abdefa3a1e8fde7e748f7de5b87daf4) ## Using TokenFlow Run the following command, specifying your file directory: ```bash theme={null} python3 launch_tokenflow.py --output_dir ``` > [accordion] Arguments > > * `output_dir`: Contains the file(s) that are to be viewed in the GUI. *\[Required]*\* `data_params:` Location of the `data_params.json` file for the preprocessed dataset. *\[Optional]*\* `port:` In case the user wants to specify a different port for the flask server. *\[Optional, default=5000]* It is assumed that `data_params.json` is present in the same directory as `output_dir`. If not, we expect it to be passed using `--data_params `. All the `.h5` files pulled from the `output_dir` are displayed in the dropdown, which are loaded when clicked. For each loaded file, all the available sequences are present in the second dropdown, which are also loaded when clicked. ## Visualized Information Given the dataset, TokenFlow displays the associated metadata, present in `data_params.json`, in the left column of the page. It also displays the distribution of sequence lengths that are present in the dataset, across the `.h5` files. On the right column, there are 4 sections. `input_strings` and `label_strings` are converted tokens from `input_ids` and `labels` respectively. The tokens in the string sections are highlighted in green when loss weight is greater than zero for that specific token. Similarly, the tokens are highlighted in red when their Attention mask is set to zero. Hovering over any token in all 4 sections highlights their corresponding token in all the other sections. This helps in checking if the mapping of an id to token, or an input to its label is correct. Additionally, the hover opens up a popup. which displays additional information like the Position IDs and the token’s idx in MSL. Also, in the case of a multimodal dataset, hovering over the image pad tokens also displays the corresponding image in the popup itself. For datasets processed in the DPO mode, the sequence selector dropdown shows sequences from the 'Chosen' section and the 'Rejected' section separately -- the format is `` or ``, where C stands for Chosen and R stands for Rejected. # Creating Custom Dataloaders Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/dataloaders/creating-custom-dataloaders Learn how to create and optimize custom PyTorch dataloaders for Cerebras systems. > [!TIP] > > Hugging Face datasets don't require conversion to use with Cerebras. Simply specify in your config file that you're using Hugging Face data. Learn more [here](https://training-docs.cerebras.ai/model-zoo/components/data-preprocessing/data-preprocessing#setup-section). ## Data Feeding in Cerebras Systems Each CS system has one or more nodes whose sole responsibility is to feed data to the system. We’ll call these nodes “worker nodes” or [input pre-processing servers](../../../concepts/cerebras-wafer-scale-cluster). So if you have a cluster of 4 CS systems and have configured your run to use 2 workers per system, then in total you will have 8 worker nodes. Workers 0 and 1 will feed data to system 0, workers 2 and 3 will feed data to system 1, etc. When you set up your model code, you supply a function that creates an instance of your dataloader. At run time, each worker node calls this function on setup to get its own independent copy of your dataloader. These worker nodes then start feeding batches to their respective CS systems in a round-robin fashion. In our 4 CS system 8 worker node example from above, this would mean that the first weight update would be performed using data from workers 0, 2, 4, and 6, then the second weight update step would be performed using data from workers 1, 3, 5, and 7. > [!NOTE] > > The number of workers is set on the `runconfig` parameters by the variable `num_workers_per_csx`. For more information about this flag in Cerebras Model Zoo models visit YAML params documentation. ### Important considerations There are a few details that you need to pay attention to when converting an existing GPU dataloader to run on CS system: * The shape and datatype of each tensor in each batch must stay the same throughout training. In practice, many dataloaders written for GPU already do this, but it’s good to double check this behavior and also to ensure that you set `drop_last=True` (yes, the batch dimension must also stay constant). * Since you stream data from each worker node independently, you need to make sure to shard your data so that you don’t encounter issues with data repetition. A given worker should have its own unique subset of the data which it is responsible for streaming, and this data should be disjoint from what other workers stream. * Speed matters. CS systems are really fast. That’s part of what makes them so useful. But all this speed means that sometimes dataloaders that are fast enough to run on GPU may end up bottlenecking speed when running on CS system. Later in this section, we will discuss more about [improve dataloader performance](../../../model-zoo/components/dataloaders/creating-custom-dataloaders#is-my-dataloader-too-slow). * If you’re not careful, your batches of data might get split up. Normally, samples in a batch are drawn IID from some global pool of samples, so we don’t really care about if batch boundary definitions are changed a little. But if your particular use case requires that samples that your dataloader batches together stay together, then you need to pay extra care. The batch size exposed to the dataloader is the global batch size, i.e. `microbatch_size * num_systems * grad_accum_steps`. However, under the hood the framework doesn’t care about what batch size the dataloader yields. Instead it repeatedly grabs the next chunk of `microbatch_size` samples from the data it has buffered and feeds these samples to the system. If this splitting of batches is unacceptable then you’ll need to implement some workarounds. However, this use case is both uncommon and advanced and so won’t be covered in detail here. ## Examples ### Converting a Map-Style Dataset Under the **Before** tab, the dataset reads a text file, tokenizes it, and slices it into samples using PyTorch [map-style dataset](https://pytorch.org/docs/stable/data.html#torch.utils.data.Dataset) paradigms. ```python Before theme={null} import torch import numpy as np from tokenizers import Tokenizer class TextDataset(torch.utils.data.Dataset): def __init__(self, input_file, sequence_length): self.sequence_length = sequence_length with open(input_file, "r") as f: text = f.read() tokenizer = Tokenizer.from_pretrained("gpt2") self.data = np.array(tokenizer.encode(text).ids, dtype=np.int32) self.data = [ self.data[i : i + self.sequence_length + 1] for i in range( 0, len(self.data) - self.sequence_length - 1, self.sequence_length ) ] def __getitem__(self, i): x = self.data[i] return { "input_ids": x[:-1], "attention_mask": np.ones(self.sequence_length, dtype=np.int32), "labels": x[1:], } def __len__(self): return (len(self.data) - 1) // self.sequence_length dataloader = torch.utils.data.DataLoader( TextDataset("/path/to/data.txt", 128), batch_size=16, shuffle=True, ) ``` ```python After theme={null} import torch import numpy as np from tokenizers import Tokenizer from modelzoo.transformers.pytorch.input_utils import num_tasks, task_id class ShardedTextDataset(torch.utils.data.Dataset): def __init__(self, input_file, sequence_length): self.sequence_length = sequence_length with open(input_file, "r") as f: text = f.read() tokenizer = Tokenizer.from_pretrained("gpt2") self.data = np.array(tokenizer.encode(text).ids, dtype=np.int32) self.data = [ self.data[i : i + self.sequence_length + 1] for i in range( 0, len(self.data) - self.sequence_length - 1, self.sequence_length ) ] self.data = self.data[task_id()::num_tasks()] def __getitem__(self, i): x = self.data[i] return { "input_ids": x[:-1], "attention_mask": np.ones(self.sequence_length, dtype=np.int32), "labels": x[1:], } def __len__(self): return (len(self.data) - 1) // self.sequence_length dataloader = torch.utils.data.DataLoader( ShardedTextDataset("/path/to/data.txt", 128), batch_size=16, shuffle=True, drop_last=True, ) ``` If you click the **After** tab, you'll notice we modified the code for CS compatibility by adding `drop_last = True.`For simpler data sharding, use the helper functions `num_tasks` and `task_id` from `modelzoo.data.common.input_utils`. They return the total number of worker nodes and the current node’s index, respectively. To create a dataloader with data sharding, you can use the `num_tasks` and `task_id` functions for efficient distribution. Here’s how you might structure the dataloader setup: To simplify the dataloader adjustment for data sharding, you only need to modify two lines: * Dataset Sharding: Within the `__init__` method of your dataset class, add a line to shard the data. This ensures each worker gets a unique subset: ```python theme={null} self.data = self.data[task_id()::num_tasks()] ``` * Drop Last Batch: When initializing the dataloader, set `drop_last = True`. This ensures that all distributed batches have the same size, avoiding issues with uneven batch sizes at the end of each epoch: ```python theme={null} dataloader = DataLoader(dataset, batch_size=..., shuffle=..., drop_last=True) ``` By sharding the dataset in the `__init__` method, you ensure that each worker node gets a distinct subset of the data, eliminating concerns about sample repetition within an epoch. Additionally, this approach works seamlessly on a GPU without needing different dataloader versions. Furthermore, you can streamline this process using your original TextDataset alongside a Cerebras-defined sampler, which automates the sharding. By integrating this sampler, you delegate the complexity of data sharding to the sampler, simplifying your dataloader configuration and making your code more maintainable: ```python theme={null} from modelzoo.data.common.h5_map_dataset.samplers import CBSampler dataset = TextDataset("/path/to/data.txt", 128) sampler = CBSampler( dataset, shuffle=True, seed=0, batch_size=16, drop_last=True, ) dataloader = torch.utils.data.DataLoader( dataset, batch_sampler=sampler ) ``` This `CBSampler` approach comes with a few additional benefits such as a data order that is independent of the number of systems you use or the number of workers streaming to each system. As with the previous example, this approach also works on GPU. ### Converting an Iterable-Style Dataset Next lets walk through an example of adapting an [iterable-style](https://pytorch.org/docs/stable/data.html#torch.utils.data.IterableDataset) dataset. The following dataset, under the **Before** tab, written for GPU has similar functionality to our previous datasets except that instead of reading all the data up front from a single text file, data is distributed across several text files each of which is read, tokenized, and split at iteration time. For the sake of brevity, this example doesn’t support multiprocessing, but in practice many dataloaders of this type might shard their data for this type of parallelism using a `worker_init_fn` or similar. ```python Before theme={null} import glob import os class ShardedIterableTextDataset(torch.utils.data.IterableDataset): def __init__(self, input_dir, sequence_length, seed): self.sequence_length = sequence_length self.files = sorted(glob.glob(os.path.join(input_dir, "*.txt"))) self.rng = np.random.default_rng(seed) self.rng.shuffle(self.files) self.tokenizer = Tokenizer.from_pretrained("gpt2") def __iter__(self): for file_name in self.files: with open(file_name, "r") as f: text = f.read() data = np.array(self.tokenizer.encode(text).ids, dtype=np.int32) data = [ data[i : i + self.sequence_length + 1] for i in range( 0, len(data) - self.sequence_length - 1, self.sequence_length ) ] self.rng.shuffle(np.array(data)) for x in data: yield { "input_ids": x[:-1], "attention_mask": np.ones(self.sequence_length, dtype=np.int32), "labels": x[1:], } dataloader = torch.utils.data.DataLoader( ShardedIterableTextDataset("/path/to/data_dir", 128, seed=0), batch_size=16 ) ``` ```python After theme={null} from modelzoo.data.common.input_utils import num_tasks, task_id class IterableTextDataset(torch.utils.data.IterableDataset): def __init__(self, input_dir, sequence_length, seed): self.sequence_length = sequence_length self.files = sorted(glob.glob(os.path.join(input_dir, "*.txt"))) self.files = self.files[task_id()::num_tasks()] self.rng = np.random.default_rng(seed) self.rng.shuffle(self.files) self.tokenizer = Tokenizer.from_pretrained("gpt2") def __iter__(self): for file_name in self.files: with open(file_name, "r") as f: text = f.read() data = np.array(self.tokenizer.encode(text).ids, dtype=np.int32) data = [ data[i : i + self.sequence_length + 1] for i in range( 0, len(data) - self.sequence_length - 1, self.sequence_length ) ] self.rng.shuffle(np.array(data)) for x in data: yield { "input_ids": x[:-1], "attention_mask": np.ones(self.sequence_length, dtype=np.int32), "labels": x[1:], } dataloader = torch.utils.data.DataLoader( IterableTextDataset("/path/to/data_dir", 128, seed=0), batch_size=16, drop_last=True ) ``` As with the previous example, the main changes we need to make are with sharding and consistency of batch shapes. We achieve this in much the same way as we did with the map style dataset. In this case, we shard the list of files to read instead of the preprocessed data itself. This way a worker node only reads and tokenizes the data it’s actually going to stream, which saves wasted work. Also note the placement of the sharding before any randomized operations. If we had elected not to seed our random number generator (by passing in `seed=None`) and had moved the line `self.files = self.files[task_id()::num_tasks()]` to the end of the `__init__` function, then the order of each worker’s copy of `self.files` might be different, in which case each worker’s list of files post sharding might not be disjoint from the lists of the other workers. Some data would get repeated, and some data would be ignored all together, which might create undesirable convergence characteristics. The only other change made was to specify `drop_last=True` to ensure that the model gets the consistency of data shape that it needs. Again, this dataloader works for both CS system and GPU. ## Improve Dataloader Performance As mentioned earlier, the speed of your dataloader can play a much larger role when trying to keep a CS system fed compared to when it only needs to feed a small number of GPUs. Luckily since all the dataloader code runs on the CPUs of the worker nodes, there’s nothing too out of the ordinary about optimizing it, and all the tricks you’re used to for optimizing the rest of the CPU code in your various applications will apply here. We’ve also built a few tools and compiled a list of a few tricks and tips to help streamline the process. ### Is my dataloader too slow? Luckily, there’s an easy way to answer this question. If your dataloader is too slow to keep up with your model, you’ll see the following warning message ```bash theme={null} WARNING: Input starvation detected Please check dataloader throughput ``` If the problem persists, the following error will be thrown ``` ERROR: Declaring stall due to input starvation, no change in status for 630 secs ``` This tells you that your model is too fast compared to the speed of your dataloader, and it’s time to start thinking of ways you can speed up your data pipeline. All things considered though, “my model is too fast” isn’t the worst problem to have, and it’s often easy enough to fix too. ## Benchmarking To start with, if your dataloader is too slow the first step is to measure its current performance so you have a solid place to start iterating from. We’ve exposed a simple tool to help do this easily while reducing boilerplate code required. ```python theme={null} import cerebras.pytorch as cstorch def make_dataloader(): dataset = ShardedIterableTextDataset("/path/to/data_dir", 128, seed=0) dataloader = torch.utils.data.DataLoader(dataset, batch_size=16, drop_last=True) return dataloader cstorch.utils.benchmark.benchmark_dataloader( input_fn=make_dataloader, num_epochs=1, steps_per_epoch=1000, ) ``` > [!NOTE] > > To execute code using `cerebras_pytorch`, use the Cerebras virtual environment. Instructions to set it up can be found here. The [`cerebras.pytorch.utils.benchmark.benchmark_dataloader`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html?highlight=cerebras%20pytorch%20utils%20benchmark%20benchmark_dataloader#dataloader-benchmark-utilities "cerebras.pytorch.utils.benchmark.benchmark_dataloader") function takes a function that creates a new dataloader as well as some arguments specifying how many steps to run for and similar. The output will look something like this ``` ################################################################## ################## Dataloader Benchmark Results ################## ################################################################## Overall statistics ------------------ Dataloader creation time: 178.2ms Total iteration time: 141.7ms Total steps: 41 Total throughput: 289.28 steps/s (4628.52 samples/s) Epoch statistics ---------------- Steps Sample Points Iterator Creation Epoch Iteration Local steps/s Global steps/s min avg max min avg max Epoch 1 41 1 166.6us 141.3ms 33.52 33.52 33.52 33.27 33.27 33.27 Unique Batch Specs ------------------- First occurence: epoch=1, epoch step=1 Total number of occurences: 41 PyTree: { 'attention_mask': 'TensorSpec(shape=(16, 128), dtype=torch.int32)', 'input_ids': 'TensorSpec(shape=(16, 128), dtype=torch.int32)', 'labels': 'TensorSpec(shape=(16, 128), dtype=torch.int32)'} ``` The dataloader benchmark results include * **Overall statistics** summary is the first place to look for useful information on the performance of your dataloader, including: * **Total throughput** line gives a view of the average speed, * **Dataloader creation time** tells you how long you’ll have to wait around for your dataloader to start up when you first launch your run. * **Epoch statistics** section shows a more detailed breakdown of the runtime. * **Unique Batch Specs** section helps to sanity check the shape and data type of the batches that get fed to the model. ### Evaluating with Simplified Datasets You may notice that this report shows that the profiling job ran for 41 steps even though we specified 1000. This is because the example profiling job above was run with a small “toy” dataset instead of something more production-scale, so there aren’t many samples in the toy dataset overall. This isn’t uncommon for real-world profiling scenarios, and it leads nicely to our next topic of discussion. One common pitfall of profiling i/o bound dataloaders using toy datasets is caching. Your OS is constantly trying to be smart and speed up your workloads as much as possible. When you write a small amount of data to disk, the OS will often cache this data in memory so that if you access it again soon, the OS can just grab the data from memory instead of doing an expensive disk read. This is awesome most of the time as it makes your code invisibly faster. However, the OS doesn’t know when you’re running a benchmark, so it’ll also speed up your benchmarking code. These optimizations will make the benchmarking code unrepresentative of the workload you’re ultimately trying to learn about. The details of how to work around this type of issue are beyond the scope of this tutorial. > [!NOTE] > > If your disk performance seems too good to be true for a toy dataset, it probably is. It might be time to dig deeper into what’s actually happening (e.g. using a tool like `iostat`). ### Optimization Strategies Now you have a handle on how fast your dataloader is running. If you decide that this speed isn’t fast enough, there are a couple of common tricks that are good to have in mind to supplement all the other speedup methods you might be thinking of. * Increase parallelism for compute bound workloads. You can do this either by increasing the number of worker processes used by your PyTorch dataloader itself or by running this dataloader across more worker nodes at the same time. With compute bound workloads this can easily increase your throughput several fold, but unfortunately it might not do much if your workload is i/o bound. * Move as much of the work as possible to pre-processing. For example, our toy datasets above tokenized the data at runtime. However, you could consider tokenizing the data at pre-processing time and reading the already tokenized data from disk at runtime. You might even consider pre-processing to one of the formats expected by our dataloaders implemented in ModelZoo if you’re interested in saving some time writing extra code. * Be mindful of where you shard. As mentioned above, it’s usually worth while to shard your data between workers as early in the pipeline as possible. This reduces the repeated work between your parallel processes. * Optimize disk access patterns for i/o bound workloads. If your data pipeline requires frequently reading small chunks of data from random locations on disk, this can reduce the total throughput of what you’re reading from disk. In many application, this won’t end up mattering, but if your profiling suggests that disk access is your primary bottleneck, then you might consider optimizing your disk access patterns. Sequential reads are much faster than random reads, so if you can think of any tricks (like shuffling your data at preprocessing time rather than runtime) that make your disk access pattern more regular, these can often speed up your i/o performance substantially. ## Conclusion Creating efficient custom dataloaders for Cerebras systems requires attention to detail in terms of batch consistency, data sharding, and performance optimization. By following the guidelines and strategies outlined in this guide, developers can effectively transition from GPU-based dataloaders to those optimized for Cerebras systems. The focus on benchmarking and practical examples ensures that dataloaders can keep up with the high-speed processing capabilities of Cerebras, ultimately leading to smoother and faster model training and inference. Leveraging these insights will help in maximizing the potential of Cerebras systems in handling complex data workflows. # Dataloaders for Pytorch Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/dataloaders/dataloaders-for-pytorch Efficient data loading is crucial for high-performance machine learning. PyTorch enhances data loading speed through parallelized data loading, batch retrieval of indices, and streaming to progressively download datasets. PyTorch offers a powerful data loading utility class (`torch.utils.data.DataLoader`). The key argument for this [DataLoader](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader) is the “Dataset”, which specifies the source of data. PyTorch supports two primary types of Datasets: > 1. [Map-style datasets](https://pytorch.org/docs/stable/data.html#torch.utils.data.Dataset) (`Dataset`) is a map from indices/keys to data samples. So, if `dataset[idx]` is accessed, that reads `idx-th` from a directory on disk. > > 2. [Iterable-style datasets](https://pytorch.org/docs/stable/data.html#torch.utils.data.IterableDataset) (`IterableDataset`) represents an iterable over data samples. This is very suitable where random reads are expensive or even improbable, and where the batch size depends on the fetched data. So, if `iter(dataset)` is called, returns a stream of data from a database, or remote server, or even logs generated in real time. In the Cerebras Model Zoo, dataloaders extend these base types to implement additional functionalities. For instance, the `BertCSVDynamicMaskDataProcessor` ([code](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/data/nlp/bert/BertCSVDynamicMaskDataProcessor.py)) extends `IterableDataset` and `BertClassifierDataProcessor` ([code](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/data/nlp/bert/BertClassifierDataProcessor.py)) extends `Dataset`. ## Properties of PyTorch Dataloader For comprehensive details on the properties of PyTorch dataloaders, refer to [this page](https://pytorch.org/docs/stable/data.html). ## Cerebras Model Zoo Dataloaders The Cerebras Model Zoo includes several example dataloaders that extend `IterableDataset` and add functionalities like input encoding and tokenization. Notable examples are: > * [BertCSVDataProcessor](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/data/nlp/bert/BertCSVDataProcessor.py) - Reads `CSV` files containing the input text tokens and `MLM` and `NSP` features > > * [GptHDF5MapDataProcessor](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/data/nlp/gpt/GptHDF5MapDataProcessor.py) - A `HDF5` map style dataset processor to read from `HDF5` format for GPT pre-training > > * [T5DynamicDataProcessor](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/data/nlp/t5/T5DynamicDataProcessor.py) - Reads text files containing the input text tokens, adds extra ids for language modelling task on the fly ## Creating a Custom Dataloader with PyTorch To create your own dataloader keep in mind these tips: 1. Ensure coherence between the dataloader output and the neural network model input: If you are using a model from the Cerebras Model Zoo, refer to the README file of the model to understand the required data format. For example, if using [GPT-2](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/gpt2/), ensure your input function produces the [features dictionary](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/gpt2#gpt-2-features-dictionary). 2. Utilize Cerebras-supported file types: Create your dataset by extending one of the native dataset types. The Cerebras ecosystem supports files of types `HDF5`, `CSV`, and `TXT`. Other file types are not tested and may not be supported. ## Conclusion Effective use of PyTorch dataloaders can dramatically improve the efficiency of your data loading processes. By leveraging the capabilities provided by PyTorch and the Cerebras Model Zoo, you can customize your data handling to meet the specific needs of your machine learning models. This ensures a streamlined, efficient workflow, enabling you to focus on model development and performance. ## What’s Next? To learn more about creating a custom dataloader, refer to our step-by-step tutorial on [Creating custom dataloaders](../../../model-zoo/components/dataloaders/creating-custom-dataloaders). # Model Zoo Config Classes Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/model-zoo-config-classes Learn about the model configuration classes in the Cerebras Model Zoo, which are used to manage and customize model settings for efficient training and deployment. When using the Cerebras Model Zoo, working with model parameters and configurations is a common and important task. To make it easy for you to define, manage, and validate model configurations, Model Zoo uses Config classes built on Pydantic's BaseModel framework. Config classes offer a robust and structured approach to managing model configurations. These classes act as detailed "schemas" that store essential model settings and enforce data type and value constraints, providing a much-needed layer of validation. Furthermore, Config classes allow developers to manage and tweak settings for each model without the need for complex code alterations. This approach fosters a more structured and adaptable environment for experimentation and fine-tuning. ## Key Advantages of Config Classes * **Validation**: By defining expected data types and constraints using Pydantic validators, Config classes significantly reduce the risk of common errors such as typos, incorrect data types, or missing fields. * **Improved Documentation**: With the structured nature of Config classes, documentation will be automatically generated from docstrings present in the class. * **Enhanced Manageability**: As models evolve to become more sophisticated, Config classes provide a clear and organized way to manage configuration parameters within the Python code. ## Config Class Hierarchy The Config classes follow a clear inheritance hierarchy: 1. **BaseConfig**: The root class that inherits from Pydantic's BaseModel, providing core validation functionality 2. **ModelConfig**: Inherits from BaseConfig, specifically for model configurations 3. **DataConfig**: Inherits from BaseConfig, specifically for data processor configurations These base classes can be imported from the cerebras.modelzoo.config module: ```python theme={null} from cerebras.modelzoo.config import BaseConfig, ModelConfig, DataConfig ``` ### BaseConfig BaseConfig is a subclass of Pydantic's BaseModel class with specific constraints. Config classes in Model Zoo are immutable by default, which means that once a config object is created, its attributes cannot be modified. This immutability helps ensure configuration stability during model execution. However, there are cases where you need to set some attributes based on other values during initialization. For these situations, the only place where attribute assignments are allowed is within the `post_init` method. For example: ```python theme={null} from cerebras.modelzoo.config import BaseConfig class SomeConfig(BaseConfig): a: int = ... # ... in pydantic means field is required b: str = "undefined" def post_init(self, context): # Only place where attribute assignments are allowed if self.a > 10: self.b = "greater than 10" else: self.b = "less than or equal to 10" ``` Alternatively, you can use Pydantic's `field_validators` to change the value of a field: ```python theme={null} import os from pydantic import field_validator from cerebras.modelzoo.config import BaseConfig class SomeConfig(BaseConfig): some_path: str @field_validator("some_path") @classmethod def change_some_path(cls, some_path): return os.path.realpath(some_path) ``` ### ModelConfig ModelConfig is a subclass of BaseConfig with the additional requirement that any config classes inheriting from it must specify a `name` field. This field's type must be defined as `Literal["name_of_the_model"]`. The value of this name field is what the system uses to determine which model to initialize. ```python theme={null} from cerebras.modelzoo.config import ModelConfig from typing import Literal class MyModelConfig(ModelConfig): name: Literal["my_model_name"] # Required field # Other model-specific fields ``` ### DataConfig DataConfig is a subclass of BaseConfig with the additional requirement that any config classes inheriting from it must specify a `data_processor` field. This field's type must be defined as `Literal["name_of_the_data_processor"]`, which ensures the field exactly matches the specific data processor identifier the system should initialize. ```python theme={null} from cerebras.modelzoo.config import DataConfig from typing import Literal class MyDataProcessorConfig(DataConfig): data_processor: Literal["name_of_the_data_processor"] # Required field # Other data processor-specific fields ``` ## Validation Mechanisms Config classes in Model Zoo provide robust validation capabilities through Pydantic's validation system. There are two main approaches to validation: * Field-level validation * Model-level validation ### Field-Level Validation Field validators check individual parameters without considering other fields. Use field-level validation when a parameter's constraints are independent of other configuration values. ```python theme={null} from pydantic import field_validator from cerebras.modelzoo.config import BaseConfig class SomeConfig(BaseConfig): some_path: str @field_validator("some_path") @classmethod def check_some_path(cls, some_path): if os.path.isabs(some_path): raise ValueError("Only relative paths allowed") return some_path ``` ### Model-Level Validation Use model validators when parameters have interdependencies or when validation requires checking multiple fields together. > [!WARNING] > > Model validators must always return self and should use mode="after". ```python theme={null} from pydantic import model_validator from cerebras.modelzoo.config import BaseConfig class SomeConfig(BaseConfig): should_be_relative: bool some_path: str @model_validator(mode="after") def check_some_path(self): if self.should_be_relative and os.path.isabs(self.some_path): raise ValueError("Only relative paths allowed") return self ``` ## Config Validation Tool Model Zoo provides a CLI tool to validate your configuration files before running your model. This helps catch configuration errors early in development. To validate a configuration file using the CLI: ```bash theme={null} cszoo config validate /path/to/params.yaml ``` ## Further Reading * For detailed information about validation mechanisms, refer to the [Pydantic validation documentation](https://docs.pydantic.dev/latest/usage/validators/). * For Model Zoo-specific implementations, review the examples in the [Model Zoo repository](https://github.com/Cerebras/modelzoo). # Model Zoo Registry Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/model-zoo-registry The Model Zoo registry serves as the central source of truth for all model definitions and their associated data processors. Through a YAML-based system, the registry maintains paths to model implementations and their compatible data processors, ensuring consistent model management across the ecosystem. This streamlined approach simplifies the process of finding available models, accessing their implementations, and identifying compatible data processing options. When working with models like BERT or GPT, the registry provides direct paths to both their implementations and data processors, allowing for quick setup and deployment. The registry can be found in the Model Zoo repository [here](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/registry/registry.yaml). > [!WARNING] > > The registry YAML file must be updated whenever models are added, moved, renamed, or removed from the Model Zoo to maintain accuracy and prevent broken references. ## Registry Structure The registry is defined in a YAML file that contains entries for each supported model. Each model entry requires three key components: * `name`: The identifier for the model * `path`: The full import path to the model's implementation class. Note: the path includes both the module path as well as the class name. * `data_processor_paths`: A list of compatible data processor implementation paths ```yaml theme={null} - name: name_of_the_model path: path.to.module.ModelClass data_processor_paths: - path.to.module.DataProcessorClass1 - path.to.module.DataProcessorClass2 ... ``` When adding new models to the Model Zoo, you must add a corresponding entry to the registry file. Similarly, when renaming, moving, or removing models, update the registry to reflect these changes. # Usage Examples Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/model-zoo-usage-examples See usage examples for common operations within Model Zoo. ## Set Up the Environment To set up your environment for Model Zoo, follow the instructions in our [getting started guide](/getting-started/setup-and-installation). ## Running an Existing Model To execute an existing model from the Cerebras Model Zoo, follow these steps: **1.** Use the CLI to query the registry and display the supported models: ```bash theme={null} cszoo model list ``` **2.** Find the model implementation. For example, to locate the path for Llama: ```bash theme={null} cszoo model info llama ``` ``` ╒═══════════════════════════════════════════════════════════════════════════════╕ │ Name │ llama ────────────────────────────────────────────────────────────────────────────────┤ │ Path │ /modelzoo/src/cerebras/modelzoo/models/nlp/llama ────────────────────────────────────────────────────────────────────────────────┤ │ Configs │ llama3p2_3b_msl_8k │ │ llama2_13b │ │ llama3p1_8b_msl_128k │ │ llama2_70b │ │ wizardlm_13b │ │ llama3p1_8b_msl_8k │ │ llama2_7b │ │ llama3p1_8b_msl_32k_swa_8k_sink_512 │ │ code_llama_7b │ │ code_llama_70b │ │ llama3p3_70b_msl_128k │ │ llama3p2_1b_msl_8k │ │ llama3p1_70b_msl_8k │ │ llama3p1_70b_msl_128k ─────────────────────────────────────────────────────────────────────────────────┤ │ Dataprocessors │ DummyDataProcessor │ │ DummyIterableDataProcessor │ │ GptHDF5DataProcessor │ │ GptHDF5MapDataProcessor │ │ HuggingFaceDataProcessorEli5 │ │ HuggingFaceIterableDataProcessorEli5 ╘═══════════════════════════════════════════════════════════════════════════════╛ ``` **3.** Determine which YAML file (under Configs above) to use for the model’s parameters. The YAML configurations are located in the -`configs` directory within the model’s folder. For example, to pull the `llama2_13b` variant config file and save it to a file called `my_params.yaml`: ```Bash theme={null} cszoo config pull llama2_13b -o my_params.yaml ``` **4.** Use the CLI to run, supplying the appropriate YAML file as an argument: ```bash theme={null} cszoo fit --params my_params.yaml ``` ### Editing Configurations If you need to modify existing configurations, ensure you have cloned the Model Zoo repository for write access to the YAML files. If you want to modify how a run is configured for a specific Model Zoo model, make sure you have first cloned the Model Zoo repository for write access to the YAML files. All reference configuration files in Model Zoo are located in the `configs/` directory. ### Querying Additional Components To see which data processors are provided in the reference examples, you can use the CLI: ```bash theme={null} cszoo data_processor list ``` ## Use Config Classes with an Existing Model Every model within the Model Zoo is equipped with a corresponding Config class. When a Config class is associated with a model, the configuration is automatically validated in the backend, necessitating no additional actions from the user. For a deeper understanding of Config classes, you can explore further details in [Model Zoo Config Classes](/model-zoo/components/model-zoo-config-classes). ## Register a Component To register a custom data processor (also known as a dataloader) or model, see [Model Zoo Registry](/model-zoo/components/model-zoo-registry). ## Evaluating Your Model To effectively evaluate your model during and after training, follow these guides: ### Evaluating During Training For insights on assessing your model’s performance throughout the training process, visit the run-model/eval guide in the Cerebras Developer Documentation. This resource provides comprehensive information on the steps and settings required to evaluate your model during training on the Wafer-Scale Cluster (WSC). ### Using EleutherAI’s Evaluation Harness If you’re working with Large Language Models (LLMs) within the Model Zoo, you might want to leverage EleutherAI’s Evaluation Harness (EEH) for a more in-depth evaluation. [Our guide](../core-workflows/downstream-validation-using-eleuther-eval-harness) on downstream valudation using EEH offers detailed instructions on how to prepare your data and set up the EEH for evaluating LLMs. This tool provides a structured approach to assessing model performance across various benchmarks and tasks, facilitating a comprehensive evaluation of your LLM. By following these guidelines, you can gain valuable insights into your model’s effectiveness, helping you make informed decisions for further model refinement and deployment. ## Adding a New Dataset To incorporate a new dataset for your model within the Cerebras Model Zoo, you’ll need to ensure it’s specified correctly in the model’s configuration and, for certain models like language models, converted into the appropriate format. ### Specifying the Dataset in the YAML Configuration **1.** Locate the YAML file Identify the YAML configuration file associated with your model. **2.** Update data\_dir Within the YAML file, under `train_input` or `eval_input` sections (depending on whether the dataset is for training or evaluation), specify the path to your dataset using the `data_dir` entry. ### Preparing Datasets for Language Models Language models within the Cerebras ecosystem often require datasets in HDF5 format. If your dataset isn’t already in this format, follow the steps in our [Data Preprocessing Quickstart guide](/model-zoo/core-workflows/quickstart-guide-for-data-preprocessing), or find more in-depth information in our [Data Preprocessing guide](/model-zoo/components/data-preprocessing/data-preprocessing). ## Utilizing Checkpoints The Cerebras Model Zoo includes a “Checkpoint and Config Converter” tool, designed to facilitate the conversion of model implementations between the Model Zoo and other frameworks or repositories. This tool is particularly useful for migrating models into the Model Zoo environment or exporting them for use in different settings. It also allows you to convert checkpoints created through running on previous Cerebras software releases to checkpoints compatible with new software releases. ### Checkpoint conversion: Cerebras and HuggingFace, software version updates To learn more about how to use this tool for converting checkpoints and model configurations, [click here](/model-zoo/migration/convert-checkpoints-and-model-configs/). This resource provides detailed instructions on using the converter, ensuring a smooth transition between different coding environments. ### Saving and Loading Checkpoints Proper checkpoint management is crucial for efficiently training and evaluating models. For guidelines on saving and loading checkpoints within the Cerebras environment, consult the [checkpointing documentation](/model-zoo/components/trainer-components/checkpointing). This section offers comprehensive insights into checkpoint handling, including saving states during training and loading them for resuming training or evaluation. By leveraging these resources, you can effectively manage model checkpoints in the Cerebras ModelZoo, enhancing your model development and experimentation workflows. # Backend Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/trainer-components/backend Learn how to set up a backend or device for the Trainer class. The [`cerebras.pytorch.backend`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#backend) is the configuration of the device and other settings used during a run. The `device` is what hardware the workflow will run on. ## Prerequisites Make sure to have read through [Trainer Overview](../../../model-zoo/trainer-overview) and [Trainer Configuration Overview](../../../model-zoo/trainer-configuration-overview) which provide the basic overview of how to run Model Zoo models. In this document, you will be using the tools and configurations outlined in those pages. ## Configure the Device Configuring the device used by the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) can be done by simply specifying one of `"CSX"`, `"CPU"`, or `"GPU"`. ```yaml YAML theme={null} trainer: init: device: "CSX" ... ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer trainer = Trainer( device="CSX", ..., ) ... ``` > [!NOTE] > > Setting `device` still creates a `cerebras.pytorch.backend` instance just with default settings. To configure anything about the backend, you must specify those parameters via the `backend` key instead. ### Limitations Once a device is set, any other `Trainer` instances must also use the same device type as well. You cannot mix device types. For example, a configuration like this: ```yaml YAML theme={null} # THIS CONFIGURATION IS INVALID trainer: - trainer: init: device: "CSX" ... ... - trainer: init: device: "CPU" ... ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer # THIS CONFIGURATION IS INVALID trainer1 = Trainer( device="CSX", ..., ) trainer2 = Trainer( device="CPU", ..., ) ... ``` will result in the following error: ```bash theme={null} RuntimeError: Cannot instantiate multiple backends. A backend with type CSX has already been instantiated. ``` ## Configure the Backend Configuring the backend used by the `Trainer` can be done by creating a `cerebras.pytorch.backend` instance. The configuration is expected to be a dictionary whose keys will be used to construct a `cerebras.pytorch.backend` instance. In the Python script, construct a `cerebras.pytorch.backend` instance and pass it to the `backend` argument. ```yaml YAML theme={null} trainer: init: backend: backend_type: "CSX" cluster_config: num_csx: 4 mount_dirs: - /path/to/dir1 - /path/to/dir2 ... ... ... ... ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( backend=cstorch.backend( backend_type="CSX", cluster_config=cstorch.distributed.ClusterConfig( num_csx=4, mount_dirs=["/path/to/dir1", "/path/to/dir2"], ..., ), ..., ) ... ) ... ``` ### Limitations Multiple backend instantiations with different devices is not supported. You will see this error: ```bash theme={null} RuntimeError: Cannot instantiate multiple backends. A backend with type CSX has already been instantiated. ``` That means that when you construct one or more `Trainer` instances, you must ensure you only instantiate backends of a single device type. However you can change other backend parameters between `Trainer` instances. The configuration is expected to be a dictionary whose keys will be used to construct a `cerebras.pytorch.backend` instance. In the Python script, construct a `cerebras.pytorch.backend` instance and pass it to the `backend` argument. For example: ```yaml YAML theme={null} trainer: - trainer: init: backend: backend_type: "CSX" cluster_config: num_csx: 4 mount_dirs: - /path/to/dir1 - /path/to/dir2 ... ... ... ... - trainer: init: backend: backend_type: "CSX" cluster_config: num_csx: 2 num_workers_per_csx: 1 mount_dirs: - /path/to/dir1 - /path/to/dir2 ... ... ... ... ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer backend = cstorch.backend( "CSX", cluster_config=cstorch.distributed.ClusterConfig( num_csx=4, mount_dirs=["/path/to/dir1", "/path/to/dir2"], ..., ), ) trainer1 = Trainer( backend=backend, ... ) backend.cluster_config.num_csx = 2 backend.cluster_config.num_workers_per_csx = 1 trainer2 = Trainer( backend=backend, ... ) ``` ## Mutual Exclusivity The `device` and `backend` arguments are mutually exclusive. It is expected when initializing a `Trainer` to set one of them but not both. If both are set, you will see an error that looks like this: ```bash theme={null} ValueError: backend and device are mutually exclusive arguments of Trainer. Please only provide one or the other ``` ## Further Reading To learn more about how you can use the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) in some core workflows, you can check out: * [Pretraining with Upstream Validation](../../../model-zoo/core-workflows/pretraining-with-upstream-validation) To learn more about how you can extend the capabilities of the `Trainer` class, you can check out: * [Defer Weight Initialization](../../../model-zoo/components/trainer-components/defer-weight-initialization) * [Numeric Precision](../../../model-zoo/components/trainer-components/numeric-precision) * [Train a model with weight sparsity](../../../model-zoo/tutorials/train-a-model-with-weight-sparsity) * [Checkpointing](../../../model-zoo/components/trainer-components/checkpointing) * [Customizing the Trainer with Callbacks](../../../model-zoo/components/trainer-components/customizing-the-trainer-with-callbacks) * [Logging](../../../model-zoo/components/trainer-components/logging) # Checkpointing Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/trainer-components/checkpointing On this page, you will learn about how to configure the checkpointing behavior of the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) with a [`Checkpoint`](https://training-api.cerebras.ai//en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#checkpoint) object. By the end you should have a cursory understanding on how to use the `Checkpoint` class in conjunction with the `Trainer`class. ## Prerequisites * You must have installed the Cerebras Model Zoo (click [here](../getting-started/setup-and-installation) if you haven’t). * You must be familiar with the [Trainer](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html). ## Configure Trainer Checkpoint Behavior Primary checkpointing functionality is done using the `Checkpoint` core callback. You can control the cadence at which you save checkpoints, the naming convention of checkpoints saved, and various other useful functionalities. For details on all options, see `Checkpoint`. An example of a checkpoint configuration is shown here: ```yaml YAML theme={null} trainer: init: checkpoint: steps: 100 save_initial_checkpoint: True checkpoint_name: "checkpoint_{step}.mdl" ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import Checkpoint trainer = Trainer( ..., checkpoint=Checkpoint( steps=100, save_initial_checkpoint=True, checkpoint_name="checkpoint_{step}.mdl", ), ) ``` In this example, you will save a checkpoint every 100 train steps. You will also save an initial checkpoint prior to training. The saved checkpoints will be named: ``` ["checkpoint_0.mdl", "checkpoint_100.mdl", "checkpoint_200.mdl", ...] ``` ### Automatically Loading from the Most Recent Checkpoint The `autoload_last_checkpoint` can be used to autoload the most recent checkpoint from `model_dir`. If you have the following checkpoints in `model_dir`: ``` ["checkpoint_0.mdl", ..., "checkpoint_19900.mdl", "checkpoint_20000.mdl"] ``` If you enable `autoload_last_checkpoint` like in the example below, the run will automatically load from the checkpoint with the largest step value, in this case `"checkpoint_20000.mdl"`. ```yaml YAML theme={null} trainer: init: checkpoint: steps: 100 autoload_last_checkpoint: True ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import Checkpoint trainer = Trainer( ..., checkpoint=Checkpoint( steps=100, autoload_last_checkpoint=True ), ) ``` ### Checkpoint Loading Strictness The `disable_strict_checkpoint_loading` option can be used to loosen the validation done when loading a checkpoint. If True, the model will not raise an error if the checkpoint contains keys that are not present in the model. ```yaml YAML theme={null} trainer: init: checkpoint: steps: 100 disable\_strict\_checkpoint_loading: True ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import Checkpoint trainer = Trainer( ..., checkpoint=Checkpoint( steps=100, disable_strict_checkpoint_loading=True ), ) ``` ## Selective Checkpoint State Saving You can specify which individual checkpoint states to be saved using the [`SaveCheckpointState`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#savecheckpointstate) callback, which allows us to: * Save an alternative checkpoint with a subset of states to conserve storage space. * Can be used to bypass [checkpoint deletion policies](#checkpoint-deletion-policy). In the example below, you will save an alternative checkpoint every 5 checkpoints saved (500 steps) that only contains the `"model"` state. > [!NOTE] > > `k` in `SaveCheckpointState` refers to taking an alterative checkpoint every `k` checkpoint steps, not every `k` steps. ```yaml YAML theme={null} trainer: init: checkpoint: steps: 100 callbacks: - SaveCheckpointState: k: 5 checkpoint_states: "model" ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ( Checkpoint, SaveCheckpointState, ) trainer = Trainer( ..., checkpoint=Checkpoint( steps=100, ), callbacks=[ SaveCheckpointState(k=5, checkpoint_states="model"), ], ) ``` ## Selective Checkpoint State Loading You can specify which individual checkpoint states to be loaded using the [`LoadCheckpointStates`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#loadcheckpointstates) callback. The `LoadCheckpointStates` callback allows us to: * Perform [fine-tuning](../../../model-zoo/core-workflows/fine-tuning-with-validation), by loading the model state but starting the optimizer state from scratch and the global step from 0. In the example below, you configure the Trainer to load only the `"model"` state from any checkpoint. ```yaml YAML theme={null} trainer: init: checkpoint: steps: 100 callbacks: - LoadCheckpointStates: load_checkpoint_states: "model" ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ( Checkpoint, LoadCheckpointStates, ) trainer = Trainer( ..., checkpoint=Checkpoint( steps=100, ), callbacks=[ LoadCheckpointStates(load_checkpoint_states="model"), ], ) ``` ## Checkpoint Deletion Policy For long runs with limited storage space, it is important to have a way to control how checkpoints are deleted or retained. To control the number of checkpoints retained, use [`KeepNCheckpoints`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#keepncheckpoints). The `KeepNCheckpoints` callback allows us to: - Constrain the amount of storage space checkpoints take up while still allowing for recent restart points in case a run is interrupted. - If you want to still keep long-term checkpoints over a larger cadence for validation purposes, checkpoints generated by [`SaveCheckpointState`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#SaveCheckpointState) are ignored by `KeepNCheckpoints` (see [Selective Checkpoint State Saving](#selective-checkpoint-state-saving) for more details). In the example below, only the 5 most recent checkpoints will be retained. ```yaml YAML theme={null} trainer: init: checkpoint: steps: 100 callbacks: - KeepNCheckpoints: n: 5 ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ( Checkpoint, LoadCheckpointStates, ) trainer = Trainer( ..., checkpoint=Checkpoint( steps=100, ), callbacks=[ KeepNCheckpoints(n=5), ], ) ``` ## What’s next? To learn how to use advanced checkpointing to do a fine-tuning run, see see [Fine-Tuning with Validation](../model-zoo/core-workflows/fine-tuning-with-validation). ## Further Reading To learn about how you can configure a [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) instance using a YAML configuration file, you can check out: * Trainer YAML Overview To learn more about how you can use the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) in some core workflows, you can check out: * [Pretraining with Upstream Validation](../model-zoo/core-workflows/pretraining-with-upstream-validation) To learn more about how you can extend the capabilities of the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) class, you can check out: * [Defer Weight Initialization](../model-zoo/components/trainer-components/defer-weight-initialization) * [Numeric Precision](../model-zoo/components/trainer-components/numeric-precision) * [Train a model with weight sparsity](../model-zoo/tutorials/train-a-model-with-weight-sparsity) * [Customizing the Trainer with Callbacks](../model-zoo/components/trainer-components/customizing-the-trainer-with-callbacks) * [Logging](../model-zoo/components/trainer-components/logging) # Customizing the Trainer with Callbacks Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/trainer-components/customizing-the-trainer-with-callbacks The [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) class was designed to be easily extendable using [`Callback`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#callback) classes. The `Trainer` exposes a number of hooks which can be overridden using a `Callback`. On this page, you will learn about the basic `Callback` mechanism. By the end you should be able to write and use your own custom `Callback`. ## Prerequisites Please ensure that you have read through the Cerebras Model Zoo Trainer Overview beforehand. The rest of this page assumes that you already have at least a cursory understanding of what the Cerebras Model Zoo Trainer is and how to use the python API. ## Callbacks The callback mechanism is the backbone of the `Trainer`’s implementation. A lot of the heavy lifting in the Trainer is actually done by various [Core Callbacks](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#core-callbacks). In general, the `Callback` mechanism exposes a number of useful hooks that allow you to inject certain behaviour into the `Trainer`. These hooks include (but are not limited to) * `setup` * `on_{fit,train,validate}_{start,end}` * `on_{train,validate}_batch_{start,end}` * `on_{after,before}_{forward,backward}` * `on_{after,before}_optimizer_{step,zero_grad}` * `on_{after,before}_scheduler_step` * `on_{save,load}_checkpoint` * `on_after_save_checkpoint` * `on_before_load_checkpoint` The following pseudocode describes the structure of the [`fit`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html#cerebras.modelzoo.Trainer.fit) call and where the various hooks get called. ```python theme={null} class Trainer: ... def fit(self, train_dataloader, val_dataloader, ckpt_path): on_before_load_checkpoint() load_checkpoint(ckpt_path) on_fit_start(...) for loop_idx in range(num_trains): on_train_start(...) for batch in train_dataloader: on_train_batch_start(...) on_before_forward(...) outputs = model(batch) on_after_forward(...) on_before_backward(...) outputs["loss"].backward() on_after_backward(...) on_before_optimizer_step(...) optimizer.step() on_after_optimizer_step(...) on_before_optimizer_zero_grad(...) optimizer.zero_grad() on_after_optimizer_zero_grad(...) for scheduler in schedulers: on_before_scheduler_step(...) scheduler.step() on_after_scheduler_step(...) on_train_batch_end(...) on_train_end(...) for batch in val_dataloader: on_validate_batch_start(...) on_before_forward(...) outputs = model(batch) on_after_forward(...) on_validate_batch_end(...) on_fit_end(...) ``` For a comprehensive list of all supported hooks (as well as the arguments they accept), see the API docs for the `Callback` class. ## Pre-packaged Callbacks There are many callbacks that come pre-packaged inside of the Model Zoo. See [Add-on Callbacks](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#add-on-callbacks) for a complete list of all the callbacks available out-of-the-box in the Model Zoo You can use any number of them to enhance the Trainer for your run. For example, ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ( ComputeNorm, CheckLoss, ... ) trainer = Trainer( ..., callbacks=[ ComputeNorm(), CheckLoss(), ... ], ... ) ... ``` ```yaml YAML theme={null} You can configure any pre-packaged callback inside a YAML configuration file as follows: trainer: init: ... callbacks: - ComputeNorm: {} - CheckLoss: {} ... ``` ## Global Callbacks Any callback can be registered globally so that all `Trainer` instances know about it and will invoke that callback’s hooks. There are two ways to globally register a callback. The first way is to treat the callback as a context manager. For example, ```python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import CheckLoss with CheckLoss(): trainer = Trainer(...) trainer.fit(...) ``` In the above example, while within the `CheckLoss`’s context, all trainer `fit` calls inside the context will check the loss values that come out of the model. The other way to register a callback is to call :py:function:`~cerebras.modelzoo.trainer.callbacks.register\_global\_callback` For example, ```python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import CheckLoss, register_global_callback callback = CheckLoss() handle = register_global_callback(callback) trainer = Trainer(...) trainer.fit(...) handle.remove() ``` In the above example, all trainer `fit` calls inside the context will check the loss values that come out of the model. :py:function:`~cerebras.modelzoo.trainer.callbacks.register\_global\_callback`returns a removeable handle object that can be used to remove the added callback by calling `handle.remove()` ## Callback Ordering The `Trainer` is comprised of many different callbacks that all serve to enhance its functionality. All of these callbacks share common hooks. These hooks must be called in a specific order. The order in which callbacks are invoked is as follows: 1. Core Callbacks: The callbacks that implement the most fundamental behaviour of the `Trainer` get called first. 2. User-defined callbacks: The callbacks that are passed into the `callbacks` argument of the `Trainer`’s constructor are called next. 3. Global callbacks: Finally, the callbacks that are registered globally are called. For example, ```python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ( CheckLoss, ComputeNorm, TrainingLoop, ) trainer = Trainer( ..., loop=TrainingLoop(num_steps=1), callbacks=[ComputeNorm()], ... ) with CheckLoss(): trainer.fit(...) ``` Let’s consider the `on_fit_start` hook. Between the three callbacks that are highlighed in the above example, the order that the callbacks’s `on_fit_start` hook is invoked is as follows: 1. `TrainingLoop.on_fit_start`: As `TrainingLoop` is a core callback. 2. `ComputeNorm.on_fit_start`: As `ComputeNorm` was passed into the Trainer’s constructor. 3. `CheckLoss.on_fit_start`: As it is a globally registered callback. ## Writing a Custom Callback To write your own custom callback class, all you need to do is inherit from the base `Callback` class and override the hooks that you need. For example, let’s implement a simple callback that scales the loss value by some constant value before we call `loss.backward()` ```python theme={null} from cerebras.modelzoo.trainer.callbacks import Callback class ScaleLoss(Callback): def __init__(self, value): self.value = value def on_before_backward(self, trainer, model, outputs): outputs["loss"] *= value ``` That is all there is to it. This callback can now be used inside the `Trainer` as follows: ```python Python theme={null} from cerebras.modelzoo import Trainer trainer = Trainer( ..., callbacks=[ScaleLoss(value=0.95)], ... ) ... ``` ```yaml YAML theme={null} As long as the callback class exists in the Python global namespace, you can add any custom callback to a YAML configuration file in exactly the same way you would any other pre-packaged callback. trainer: init: ... callbacks: - ScaleLoss: value: 0.95 ... ``` In order for the callback class to exist in the Python global namespace, the Python interpreter must have seen it at some point. Implementing your custom callback in the same file as the model class ensures that the callback is seen by the Python interpreter and loaded into the Python global namespace. # Defer Weight Initialization Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/trainer-components/defer-weight-initialization By deferring the initialization of model weights, you can significantly reduce the time-to-first-loss, leading to faster iteration times and a more efficient training process. In this page, you will explore how to defer model weight initialization using the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) class. By the end of this guide, you will understand how to implement deferred initialization and the advantages it brings to your model training. ## Prerequisites Please ensure that you have read through the [Trainer Overview](../../../model-zoo/trainer-overview) beforehand. The rest of this page assumes that you already have at least a cursory understanding of what the Cerebras Model Zoo Trainer is and how to use the python API. ## Model Function In [Basic Usage](../../../model-zoo/trainer-overview), it was shown that you could pass any [`torch.nn.Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module "(in PyTorch v2.4)") into the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html). However, to do this, you need to have a concrete [`torch.nn.Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module "(in PyTorch v2.4)") object to pass into the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html). Due to PyTorch’s eager nature, initializing a model can be very time consuming, especially for extremely large models. To improve your experience, we introduce a mechanism by which you can defer your model’s weight initialization. The way to do this would be to pass in a function to the `model` argument of the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) that takes in no arguments and returns a [`torch.nn.Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module "(in PyTorch v2.4)") object. ```python theme={null} import torch from cerebras.modelzoo import Trainer def model_fn() -> torch.nn.Module: ... trainer = Trainer( device="CSX", model=model_fn, ... ) ``` Any callable that matches this schema is accepted. So, you could construct your model inline using a `lambda` function as follows. ```python theme={null} import torch trainer = Trainer( device="CSX", model=lambda: torch.nn.Linear(784, 10), ... ) ``` Passing in a model function will allow the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) to employ the use of the [Efficient weight initialization](../../../cs-torch/writing-a-custom-training-loop/efficient-weight-initialization) mechanism built into the Cerebras PyTorch API. Empirically, deferring model weight initialization can reduce the time-to-first-loss (the amount of time it takes to get the first value back from the Wafer-Scale Cluster) by over 50%. This means, less time waiting around and faster iteration time overall. ## Optimizer/Scheduler Functions One question that may be on your mind is, “what about the optimizer?”. The optimizer constructor takes in the model parameters. So, if the model initialization is being delayed, then how can the optimizer be constructed? The answer is that the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) can also accept a function for the `optimizer` argument which is expected to take in a [`torch.nn.Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module "(in PyTorch v2.4)") and return a [`Optimizer`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.Optimizer) object. ```python theme={null} import cerebras.pytorch as cstorch import torch trainer = Trainer( device="CSX", model=lambda: torch.nn.Linear(784, 10), optimizer=lambda model: cstorch.optim.SGD( model.parameters(), lr=0.01, momentum=0.9, ), ... ) ``` Similarly, the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) can also accept a function for the `schedulers` argument which is expected to take in a [`Optimizer`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.Optimizer) object and return a [`Scheduler`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.scheduler.Scheduler) object. ```python theme={null} import cerebras.pytorch as cstorch import torch trainer = Trainer( device="CSX", model=lambda: torch.nn.Linear(784, 10), optimizer=lambda model: cstorch.optim.SGD( model.parameters(), lr=0.01, momentum=0.9, ), schedulers=[ lambda optimizer: cstorch.optim.lr_scheduler.LinearLR( optimizer, initial_learning_rate=0.01, end_learning_rate=0.01, total_iters=100, ), ], ) ``` ## Conclusion That is all there is to deferring model, optimizer, and scheduler initialization! By simply wrapping these components inside a callable, you can gain large improvements to iteration time and resource utilization, enhancing your overall experience with the Cerebras Model Zoo and ensuring more efficient training outcomes. ## Further Reading To learn about how you can configure a [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) instance using a YAML configuration file, you can check out: * Trainer YAML Overview To learn more about how you can use the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) in some core workflows, you can check out: * [Pretraining with Upstream Validation](../../../model-zoo/core-workflows/pretraining-with-upstream-validation) To learn more about how you can extend the capabilities of the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) class, you can check out: * [Numeric Precision](../../../model-zoo/components/trainer-components/numeric-precision) * [Train a model with weight sparsity](../../../model-zoo/tutorials/train-a-model-with-weight-sparsity) * [Checkpointing](../../../model-zoo/components/trainer-components/checkpointing) * [Customizing the Trainer with Callbacks](../../../model-zoo/components/trainer-components/customizing-the-trainer-with-callbacks) * [Logging](../../../model-zoo/components/trainer-components/logging) # Logging Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/trainer-components/logging The [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) class features an extendable logging mechanism that can be used to log metrics to various backends. On this page, you will learn about how to set up logging to the console via the [`Logging`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#cerebras.modelzoo.trainer.callbacks.Logging) class as well as how to add [`Logger`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.loggers.html#cerebras.modelzoo.trainer.loggers.Logger) classes to the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) as well. ## Prerequisites Please ensure that you have read through the Cerebras Model Zoo Trainer Overview beforehand. The rest of this page assumes that you already have at least a cursory understanding of what the Cerebras Model Zoo Trainer is and how to use the python API. Also, make sure that you've read through [Customizing the Trainer with Callbacks](../../../model-zoo/components/trainer-components/customizing-the-trainer-with-callbacks) as this page will assume that you are familiar with the [`Callback`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#cerebras.modelzoo.trainer.callbacks.Callback) mechanism. ## Logging to Console The [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) exposes a [`logger`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.loggers.html#cerebras.modelzoo.trainer.loggers.Logger) attr which returns a Python logger object which can be used to log various messages to the console with different levels. For example, ```python theme={null} from cerebras.modelzoo import Trainer trainer = Trainer(...) trainer.loggers.info("This is an INFO message") trainer.loggers.debug("This is a DEBUG message") trainer.loggers.warning("This is a WARNING message") trainer.loggers.error("This is a ERROR message") ``` The [`logger`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.loggers.html#cerebras.modelzoo.trainer.loggers.Logger) can be configured by passing in a [`Logging`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#cerebras.modelzoo.trainer.callbacks.Logging) object to the `Trainer`’s constructor. ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import Logging trainer = Trainer( ..., logging=Logging( log_steps=1, log_level="INFO", ), ..., ) ... ``` ```yaml YAML theme={null} trainer: init: ... logging: log_steps: 1 log_level: INFO ... ... ``` In the above example, the [`logger`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.loggers.html#cerebras.modelzoo.trainer.loggers.Logger) has been configured to print `INFO` messages to the console by default. See [Control Logging Frequency](#control-logging-frequency) for an explanation of the `log_steps` argument. ## Logging Metrics The way to log metrics using the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) is to construct and pass in [`Logger`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.loggers.html#cerebras.modelzoo.trainer.loggers.Logger) subclasses. Included out-of-the-box are * [`ProgressLogger`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.loggers.html#cerebras.modelzoo.trainer.loggers.ProgressLogger): Logs progress metrics to the console * [`TensorBoardLogger`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.loggers.html#cerebras.modelzoo.trainer.loggers.TensorBoardLogger): Logs metrics to a TensorBoard event file. These [`Logger`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.loggers.html#cerebras.modelzoo.trainer.loggers.Logger) subclasses can be constructed and passed into the trainer via the `loggers` argument: ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.loggers import ( ProgressLogger, TensorBoardLogger, ) trainer = Trainer( ..., loggers=[ ProgressLogger(), TensorBoardLogger(), ] ..., ) ... ``` ```yaml YAML theme={null} trainer: init: ... loggers: - ProgressLogger: {} - TensorBoardLogger: {} ... ... ``` With these loggers, you can now call [`trainer.log_metrics`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html#cerebras.modelzoo.Trainer.log_metrics) to log some metric to all loggers. ```python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.loggers import TensorBoardLogger trainer = Trainer( ..., loggers=[TensorBoardLogger()] ..., ) trainer.log_metrics(loss=...) ``` In the above example, the `loss` is being logged to the [`TensorBoardLogger`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.loggers.html#cerebras.modelzoo.trainer.loggers.TensorBoardLogger) at the current global step. ## Logging Name Scope The trainer also features a [`name_scope`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html#cerebras.modelzoo.Trainer.name_scope) mechanism for logging which is intended to be used to group related logs together. ```python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.loggers import TensorBoardLogger trainer = Trainer( ..., loggers=[TensorBoardLogger()] ..., ) with trainer.name_scope("train"): trainer.log_metrics(loss=...) trainer.log_metrics(accuracy=...) ``` In the above example, the metrics get recorded in the log as `train/loss` and `train/accuracy`. ## Control Logging Frequency It is often the case in very long runs that logging metrics every step is undesirably verbose. To remedy this, you can specify `log_steps` to the [`Logging`](ttps://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#cerebras.modelzoo.trainer.callbacks.Logging) class. ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import Logging trainer = Trainer( ..., logging=Logging(log_steps=10), ..., ) ... ``` ```yaml YAML theme={null} trainer: init: ... logging: log_steps: 10 ... ... ``` In the above example, the trainer is configured to log metrics every 10 steps. This means that even if [`log_metrics`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html#cerebras.modelzoo.Trainer.log_metrics) is called every step, only every 10 steps does the metric actually get logged. To query whether or not current step is a log step, you can call [`trainer.is_log_step`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html#cerebras.modelzoo.Trainer.is_log_step). ## Writing a Custom Logger Now that you know all about the [`Logger`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.loggers.html#cerebras.modelzoo.trainer.loggers.Logger") class and how it’s integrated into the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) class, it is fairly straightforward to write your own custom loggers. To write your own custom Logger class, all you need to do is inherit from the base [`Logger`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.loggers.html#cerebras.modelzoo.trainer.loggers.Logger") class and override the following methods: * `log_metrics`: Logs the provided metrics at the provided step. * `flush`: Flushes the logs For example, let’s implement a simple logger that just logs the metrics to console ```python theme={null} from cerebras.modelzoo.trainer.logger import Logger class ConsoleLogger(Logger): def setup(self, trainer): self.trainer = trainer def flush(self): for handler in self.trainer.loggers.handlers: handler.flush() def log_metrics(self, metrics, step): for name, value in metrics.items(): self.trainer.loggers.info( f"Step={step}, {name}={value} ) ``` > [!NOTE] > > Note > > All [`Logger`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.loggers.html#cerebras.modelzoo.trainer.loggers.Logger") instances inherit from [`Callback`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#cerebras.modelzoo.trainer.callbacks.Callback). This means that loggers may override any of the hooks that are exposed via the [`Callback`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#cerebras.modelzoo.trainer.callbacks.Callback) mechanism too. That is all there is to it. This logger can now be used inside the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) as follows: ```python Python theme={null} from cerebras.modelzoo import Trainer trainer = Trainer( ..., logger=[ConsoleLogger()], ... ) ... ``` ```yaml YAML theme={null} As long as the logger class exists in the Python global namespace, you can add any custom logger to a YAML configuration file in exactly the same way you would any other pre-packaged loggers. trainer: init: ... loggers: - ConsoleLogger: {} ... ``` In order for the callback class to exist in the Python global namespace, the Python interpreter must have seen it at some point. Implementing your custom logger in the same file as the model class or ensuring it is properly imported and referenced in your CLI workflow are two ways to ensure that the logger is recognized and loaded into the Python global namespace. # Loop Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/trainer-components/loop Learn how to configure the training and validation loops of the Trainer using two `LoopCallback` subclasses. ## Prerequisites Read the [Trainer Overview](../../../model-zoo/trainer-overview) and [Trainer Configuration Overview](../../../model-zoo/trainer-configuration-overview) for a basic overview of how to run Model Zoo models. ## Configure the Loop The `loop` argument allows you to manage the training and/or validation loop. The [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) takes in a [`LoopCallback`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#cerebras.modelzoo.trainer.callbacks.LoopCallback "cerebras.modelzoo.trainer.callbacks.LoopCallback") subclass that is used to configure loop options such as number of steps/epochs to run for and how often to run validation. A `LoopCallback` cannot be instantiated directly, [`TrainingLoop`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#cerebras.modelzoo.trainer.callbacks.TrainingLoop "cerebras.modelzoo.trainer.callbacks.TrainingLoop") or [`ValidationLoop`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#cerebras.modelzoo.trainer.callbacks.ValidationLoop "cerebras.modelzoo.trainer.callbacks.ValidationLoop") must be used instead. ### Configure for training The `TrainingLoop` callback is used to configure the `Trainer` to run a `fit` task. The majority of loop arguments reference `step`. The `step` is simply a batch of training/validation data. **Arguments** * `num_steps`: The total number of steps to train for. * `max_steps`: The maximum number of global steps to train for. `num_steps` supersedes this. * `num_epochs`: The number of epochs to train for. Mutually exclusive with `num_steps`. * `steps_per_epoch`: The number of steps to train for in each epoch. * `eval_frequency`: The frequency at which validation is performed. See `LoopCallback` for more details on options. * `eval_steps`: The number of validation steps to perform. * `grad_accum_steps`: The number of steps to accumulate gradients before performing and optimizer step. Only relevant for `"CPU"` and `"GPU"` runs. > [!NOTE] > > If you plan on running any kind of training (calling `fit`), you must use a `TrainingLoop`. If you plan on running **only** validation, you may use a `ValidationLoop`. In the example below, we configure the `Trainer` to run for 1000 steps and run validation for 50 steps every 100 training steps. ```yaml YAML theme={null} trainer: init: ... loop: num_steps: 1000 eval_steps: 50 eval_frequency: 100 ... fit: ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import TrainingLoop trainer = Trainer( ..., loop=TrainingLoop( num_steps=1000, eval_steps=50, eval_frequency=100, ), ..., ) trainer.fit(...) ``` ### Configure for Validation The `ValidationLoop` callback is used to configure the `Trainer` to run a `validate` or `validate_all` task. **Arguments** * `eval_steps`: The number of validation steps to perform. * `hook`: The base name of the validation hooks to run. Used to extend validation functionality by implementing custom validation callbacks. See `EleutherEvalHarnessLoop` for an example. Defaults to `"validate"`. > [!NOTE] > > `ValidationLoop` can only be used if you plan on running **only** validation tasks (calling `validate` or `validate_all`). Otherwise, use `TrainingLoop`. In the example below, we configure the `Trainer` to run validation for 100 steps. We do not need to set any training related options such as `num_steps` or `eval_frequency` since we are only running validation. ```yaml YAML theme={null} trainer: init: ... loop: eval_frequency: 100 ... validate: ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ValidationLoop trainer = Trainer( ..., loop=ValidationLoop( eval_frequency=100, ), ..., ) trainer.validate(...) ``` > [!NOTE] > > `TrainingLoop` supports both training and validation because it instantiates a `ValidationLoop` on initalization. > [!NOTE] > > Everytime validation runs, we are restarting the validation dataloaders from scratch. This is not the same for training where we resume training from the where we left off in the training dataloader. # Model Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/trainer-components/model Learn how to pass a model to the Trainer class. The `model` is the main [`Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module "(in PyTorch v2.4)") that all training and validation is run on. It's required by all [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) instances. ## Prerequisites Read the [Trainer Overview](../../../model-zoo/trainer-overview) and [Trainer Configuration Overview](../../../model-zoo/trainer-configuration-overview) for a basic overview of how to run Model Zoo models. ## Configure the Model Use the `model` argument to set the model you'd like to train or validate. When using YAML, pass all `model` subkeys as arguments to the model class. Your run script's `model_fn` determines the model class. In Python, you can specify the model in two ways: * As a callable that takes no arguments and returns a `Module` * As a `Module` that the system uses directly ```yaml YAML theme={null} trainer: init: ... model: vocab_size: 1024 max_position_embeddings: 1024 ... ... ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model trainer = Trainer( ..., model=lambda: Gpt2Model( vocab_size=1024, max_position_embeddings=1024, ..., ), ..., ) ... ``` > [!NOTE] > > When passing a `Module` directly, initialize the model inside the Cerebras device context for optimal performance: > > ```python theme={null} > import cerebras.pytorch as cstorch > from cerebras.modelzoo import Trainer > from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model > > # Initialize the Cerebras backend for efficient processing. > backend = cstorch.backend("CSX") > > # Use the backend's device context manager for initializing the model. > with backend.device: > model = Gpt2Model( > vocab_size=1024, > max_position_embeddings=1024, > ..., > ) > > # Compile the model using the Cerebras backend for optimized execution. > trainer = Trainer( > ..., > backend=backend, > model=model, > ..., > ) > ... > ``` > > This approach automatically moves model parameters to the Cerebras device, optimizing memory usage and improving initialization speed. For more information, see [Efficient weight initialization](../../../cs-torch/writing-a-custom-training-loop/efficient-weight-initialization). # Model Directory Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/trainer-components/model-directory ## Prerequisites Read through the [Trainer Overview](../../../model-zoo/trainer-overview) and [Trainer Configuration Overview](../model-zoo/trainer-configuration-overview). In this guide, you'll use the tools and configurations outlined in those pages. ## Configure the Model Directory Pass the `model_dir` argument to the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) constructor to set the model directory for trainer artifacts: ```yaml YAML theme={null} trainer: init: ... model_dir: "./model_dir" ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( ..., model_dir="./model_dir", ) ``` ## Model Directory Structure THe model directory contains a subdirectory named after the datetime for the run. This allows multiple runs to use the same model directory. ```bash theme={null} model_dir/ ├── 20240618_074134 │ ├── eleuther_0 │ │ └── results │ │ ├── drop_10.json │ │ ├── drop_5.json │ │ ├── results_10.json │ │ ├── results_5.json │ │ ├── winogrande_10.json │ │ └── winogrande_5.json │ ├── events.out.csevents.1718721695.user.17833.0 │ │ └── ... │ └── events.out.tfevents.1718721695.user.17833.0 ├── cerebras_logs │ ├── 20240618_074134 │ │ ├── run.log │ └── ... ├── checkpoint_10.mdl ├── checkpoint_5.mdl └── latest_run.log -> cerebras_logs/20240618_074134/run.log ``` Inside this subdirectory are results from the run. In the above example, you can see the results from an [Eleuther Eval Harness run](../../../model-zoo/core-workflows/downstream-validation-using-eleuther-eval-harness). This run also used the [`TensorBoardLogger`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.loggers.html#cerebras.modelzoo.trainer.loggers.TensorBoardLogger) and includes the event files that were written by the TensorBoard writer. > [!NOTE] > > If you open Tensorboard to the model directory, the runs are grouped together by run. > > ``` > tensorboard --bind_all --logdir=./model_dir > > ``` Inside the model directory, the `cerebras_logs` directory stores various logs and artifacts from compilation and execution. These logs and artifacts are organized by datetime, matching the previously mentioned subdirectory, to help associate them with specific runs. Checkpoints taken during the run are also saved in the base model directory, allowing future runs with checkpoint autoloading enabled to access them easily. See [Checkpointing](../../../model-zoo/components/trainer-components/checkpointing) for more details. # Numeric Precision Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/trainer-components/numeric-precision One thing you can do to enhance performance is to play around with the numeric precision level. Using lower precisions can drastically improve performance at the cost of numeric precision. For optimal performance and numeric stability, it is essential to utilize all the recommended methods. This page will cover how you can configure numeric precision using the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) and ways you can mitigate some of the adverse effects of using lower precision. ## Prerequisites Please ensure that you have read through the [Trainer Overview](../../../model-zoo/trainer-overview) beforehand. The rest of this page assumes that you already have at least a cursory understanding of what the Cerebras Model Zoo Trainer is and how to use the python API. Also, read through the [Gradient scaling](../../../cs-torch/writing-a-custom-training-loop/gradient-scaling) guide for more context on the concepts being used below. ## Automatic Mixed Precision Using a lower precision for computating activations while storing weights in a higher precision is a good way to get improved performance whilst keeping some numeric stability. To facilitate this, you can construct a [`MixedPrecision`](https://docs.cerebras.net/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#cerebras.modelzoo.trainer.callbacks.MixedPrecision"cerebras.modelzoo.trainer.callbacks.MixedPrecision") instance and pass it into the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html)’s `precision` argument as follows. ```yaml YAML theme={null} trainer: init: ... precision: fp16_type: cbfloat16 ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import MixedPrecision trainer = Trainer( ..., precision=MixedPrecision( fp16_type="cbfloat16", ), ) ``` In the above example, the lower precision type is set to `cbfloat16`. The supported lower precision values include: * `float16` * `bfloat16` * `cbfloat16` > [accordion] About CB16 Half-Precision > > CB16 is Cerebras’ 16-bit format, also referred to as `cbfloat16`. It's a floating-point format with 6-bit exponent and 9-bit explicit mantissa. This allows for double the dynamic range of FP16. > > ![CB16 format](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/cbfloat16-format.jpg?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=1082f2bcfbd23f9f6faacb945e44e7ea) > > With 1 more bit for the exponent compared to FP16, CB16 provides a bigger range with the following benefits: > > * Denormals are far less frequent. > > * Dynamic loss scaling is not necessary on many networks. > > > [!NOTE] > > > > The `cbfloat16` data format is different from the bfloat16 [Brain Floating Point](https://en.wikipedia.org/wiki/Bfloat16_floating-point_format) format. ## Gradient Scaling When using a lower numeric precision, you will often encounter gradient underflow. To mitigate this, you can employ gradient scaling (see [Gradient scaling](../cs-torch/writing-a-custom-training-loop/gradient-scaling) for a more in-depth explanation). To configure gradient scaling, you can pass in the `loss_scaling_factor` argument to [`MixedPrecision`](https://https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#cerebras.modelzoo.trainer.callbacks.MixedPrecision"cerebras.modelzoo.trainer.callbacks.MixedPrecision") as follows: ```yaml YAML theme={null} trainer: init: ... precision: fp16_type: cbfloat16 loss_scaling_factor: dynamic ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import MixedPrecision trainer = Trainer( ..., precision=MixedPrecision( fp16_type="cbfloat16", loss_scaling_factor="dynamic", ), ) ``` `loss_scaling_factor` accepts either some `float` for static loss scaling, or the string `"dynamic"` to facilitate dynamic loss scaling (see [Dynamic loss scaling](../model-zoo/tutorials/dynamic-loss-scaling) for more details). ## Gradient Clipping Even with all of the above, you may encounter exploding gradients (`inf` or `NaN` gradients). To mitigate this, you can employ the use of gradient clipping. To configure gradient clipping, you can pass in one of `max_gradient_norm` or `max_gradient_value` to [`MixedPrecision`](https://https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#cerebras.modelzoo.trainer.callbacks.MixedPrecision"cerebras.modelzoo.trainer.callbacks.MixedPrecision") as follows: ```yaml YAML theme={null} trainer: init: ... precision: fp16_type: cbfloat16 loss_scaling_factor: dynamic max_gradient_norm: 1.0 # OR max_gradient_value: 2.0 ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import MixedPrecision trainer = Trainer( ..., precision=MixedPrecision( fp16_type="cbfloat16", loss_scaling_factor="dynamic", max_gradient_norm=1.0, # OR max_gradient_value=2.0, ), ) ``` These two arguments correspond directly to calls to * [torch.nn.utils.clip\_grad\_norm\_](https://pytorch.org/docs/stable/generated/torch.nn.utils.clip_grad_norm_.html) * [torch.nn.utils.clip\_grad\_value\_](https://pytorch.org/docs/stable/generated/torch.nn.utils.clip_grad_value_.html) > [!NOTE] > > `max_gradient_norm` and `max_gradient_value` are mutually exclusive. So, only one may be passed in. ## Precision Optimization Level (POL) One additional setting you can configure to improve performance is to set the precision optimization level used by the Cerebras compiler. The precision optimization level (POL) to use when compiling the model. The POL determines the level of precision to use for the model’s weights and activations and can thus affect the model’s accuracy and performance. You can set the precision optimization level by passing in the `precision_opt_level` argument to [`MixedPrecision`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#cerebras.modelzoo.trainer.callbacks.MixedPrecision"cerebras.modelzoo.trainer.callbacks.MixedPrecision") as follows: ```yaml YAML theme={null} trainer: init: ... precision: fp16_type: cbfloat16 loss_scaling_factor: dynamic max_gradient_norm: 1.0 precision_opt_level: 1 ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import MixedPrecision trainer = Trainer( ..., precision=MixedPrecision( fp16_type="float16", loss_scaling_factor="dynamic", max_gradient_norm=1.0, precision_opt_level=1, ), ) ``` The value must be one of `[0, 1, 2]`. The precision optimization level is set to `1` by default. ## Conclusion That is all there is to know about configuring numeric precision in the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html)! ### Further Reading To learn more about how you can extend the capabilities of the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) class, you can check out: * [Defer Weight Initialization](../../../model-zoo/components/trainer-components/defer-weight-initialization) * [Train a model with weight sparsity](../../../model-zoo/tutorials/train-a-model-with-weight-sparsity) * [Checkpointing](../../../model-zoo/components/trainer-components/checkpointing) * [Customizing the Trainer with Callbacks](../../../model-zoo/components/trainer-components/customizing-the-trainer-with-callbacks) * [Logging](../../../model-zoo/components/trainer-components/logging) # Optimizer And Scheduler Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/trainer-components/optimizer-and-scheduler On this page, you will learn about how to add and configure the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) with a [`Optimizer`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.Optimizer) and with one or more [`Scheduler`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.scheduler.Scheduler) classes. By the end you should have a cursory understanding on how to use the [`Optimizer`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.Optimizer) class and [`Scheduler`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.scheduler.Scheduler) class in conjunction with the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) class. ## Prerequisites * You must have installed the Cerebras Model Zoo (click [here](../../../getting-started/setup-and-installation) if you haven’t). * You must be familiar with the [Trainer](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html). * Please ensure you have an understanding of the CSTorch optimizer and scheduler classes by reading the [cerebras.pytorch.optim](../../../cs-torch/cerebras-pytorch-api/cerebras-pytorch-optim) docs. ## Basic Usage An [`Optimizer`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.Optimizer) implements an optimization algorithm to control how model parameters are updated. Various hyperparameters such as `lr`, `momentum`, and `weight_decay` can be passed to the [`Optimizer`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.Optimizer) to give further control. A [`Scheduler`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.scheduler.Scheduler) is used in conjunction with an [`Optimizer`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.Optimizer) to adjust the value of these hyperparameters over the course of a run. Currently, schedulers for `lr` and `weight_decay` are supported. The [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) takes in an `optimizer` argument. An optimizer is used to optimize model weights during training and is required for any run that does any training. `optimizer` can be passed as an [`Optimizer`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.Optimizer) class. For details on all available optimizers, see the [CSTorch optimizer class](../cs-torch/cerebras-pytorch-api/cerebras-pytorch-optim). The [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) also accepts a `schedulers` argument. Schedulers are used to adjust hyperparameters during training. Typically this adjustment is a decay following some algorithm. The CSTorch API supports schedulers that adjust either learning rate or weight decay. For a full list of available schedulers see [CSTorch scheduler class](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#lr-scheduler-class-docs). In the example below, you create an SGD optimizer with a single SequentialLR Scheduler that is a LinearLR Scheduler for the first 500 steps, then a CosineDecayLR Scheduler for the next 500 steps. ```yaml YAML theme={null} trainer: init: optimizer: # Corresponds to cstorch.optim.SGD SGD: lr: 0.01 momentum: 0.9 schedulers: - SequentialLR: schedulers: - LinearLR: initial_learning_rate: 0.01 end_learning_rate: 0.001 total_iters: 500 - CosineDecayLR: initial_learning_rate: 0.001 end_learning_rate: 0.0001 total_iters: 500 ... ... ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( ..., optimizer=lambda model: cstorch.optim.SGD( model.parameters(), lr=0.01, momentum=0.9, ), schedulers=[ lambda optimizer: cstorch.optim.lr_scheduler.SequentialLR( optimizer, schedulers=[ cstorch.optim.lr_scheduler.LinearLR( optimizer, initial_learning_rate=0.01, end_learning_rate=0.001, total_iters=500, ), cstorch.optim.lr_scheduler.CosineDecayLR( optimizer, initial_learning_rate=0.001, end_learning_rate=0.0001, total_iters=500, ), ] ), ... ], ..., ) ... ``` > [!NOTE] > > Note how in python, `optimizer` is passed as a callable, assumed to be a function that takes in a torch.nn.Module and returns a [`Optimizer`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.Optimizer). It can also be passed as an [`Optimizer`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.Optimizer) provided the `model` is already defined. > > Similarly `schedulers` is passed as a list of callables, where each element is assumed to be a function that takes in a [`Optimizer`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.Optimizer) and returns a [`Scheduler`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.scheduler.Scheduler). It can also be passed as an [`Scheduler`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.scheduler.Scheduler) provided the `Optimizer` is already defined. > > Using callables allows us to pass in objects without having to predefine inputs to that object. ## Using Tags to Selectively Update You can use ModelZoo to filter what parameters a scheduler will update. This is done on the optimizer-side by tagging `param_groups` based on glob-like patterns and on the scheduler-side by specifying which tagged groups to update. ### Generating tags in the Optimizer The optimizer contains an attribute `param_groups` which is a list of dictionaries containing all parameters. For more information see the [PyTorch documentation](https://pytorch.org/docs/stable/optim.html#per-parameter-options). Modelzoo has the ability to tag optimizer `param_groups` based on glob-like pattern matching of parameter names. These tagged `param_groups` can then be used to selectively adjust specific parameters. Parameters are partitioned and tagged via YAML. For example: ```yaml YAML theme={null} trainer: init: optimizer: Adam: lr: 0.005 params: - params: "*bias" tag: "bias_params" ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.common.optim_utils import partition_params_group_with_tags filter_params = { "params": [{"params": "*bias", "tag": "bias_params"}], } trainer = Trainer( ..., optimizer=lambda model: cstorch.optim.SGD( partition_params_group_with_tags(model.parameters(), filter_params), lr=0.01, momentum=0.9, ), ..., ) ... ``` This specification would group all parameters whose names end in `"bias"` into one group with the tag `"bias_params"`. All remaining parameters would be in another group with no tags. For cases where multiple filters are specified and target overlapping subsets, `param_groups` will be partitioned into all unique combinations of tags. For example, if you had parameters named: ``` fc1.weight fc1.bias fc2.weight fc2.bias ``` Given these filters: ``` params: - params: "*bias" tag: "bias_params" - params: "fc1*" tag: "fc1_params" ``` You will end up with params groups partitioned like this: ``` [ {"tags": set("bias_params"), "params": ("fc2.bias", ...)}, {"tags": set("fc1_params"), "params": ("fc1.weight", ...)}, {"tags": set("bias_params", "fc1_params"), "params": ("fc1.bias", ...)}, {"params": ("fc2.weight", ...)}, ] ``` Currently, the main application for parameter tagging is for selectively applying schedulers to specific parameters. > [!NOTE] > > By default, ModelZoo may perform other partitioning operations on `param_groups`. This may affect the length of `param_groups` however the placement of `"tags"` will still be correctly preserved. See [`configure_param_groups`](https://training-api.cerebras.ai/en/latest/wsc/port/_autosummary/cerebras.modelzoo.common.optim_utils.configure_param_groups.html#cerebras.modelzoo.common.optim_utils.configure_param_groups) for more details. ### Specifying tags in the Scheduler Using the `param_group_tags` argument, individual schedulers can be configured to only target specific optimizer `param_groups`. For example: ```yaml YAML theme={null} trainer: init: schedulers: - LinearLR: initial_learning_rate: 0.01 end_learning_rate: 0.001 total_iters: 100 param_group_tags: "tag1" ... ... ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( ..., schedulers=[ lambda optimizer: cstorch.optim.lr_scheduler.LinearLR( optimizer, initial_learning_rate=0.01, end_learning_rate=0.001, total_iters=100, param_group_tags="tag1", ), ... ], ..., ) ... ``` In the example above, the learning rate scheduler specified will only update optimizer `param_groups` that have the `"tag1"` tag. These tags can be added to `param_groups` manually but the most common use case is in conjunction with [optimizer tagging](#generating-tags-in-the-optimizer). ```yaml YAML theme={null} trainer: init: optimizer: Adam: lr: 0.005 params: - params: "*bias" tag: "bias_params" schedulers: - CosineDecayWD: initial_weight_decay: 0.01 end_weight_decay: 0.001 total_iters: 100 param_group_tags: "bias_params" ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.common.optim_utils import partition_params_group_with_tags filter_params = { "params": [{"params": "*bias", "tag": "bias_params"}], } trainer = Trainer( ..., optimizer=lambda model: cstorch.optim.SGD( partition_params_group_with_tags(model.parameters(), filter_params), lr=0.01, momentum=0.9, ), schedulers=lambda optimizer: cstorch.optim.weight_decay_scheduler.CosineDecayWD( optimizer, initial_weight_decay=0.01, end_weight_decay=0.001, total_iters=100, param_group_tags="bias_params", ) ..., ) ... ``` In the example above, the `CosineDecayWD` scheduler would only adjust the weight decay of parameters whose names end in `"bias"`. ## Conclusion That concludes this overview of using the [`Optimizer`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.Optimizer) and the [`Scheduler`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.scheduler.Scheduler) in conjunction with the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html). By this point, you should have a cursory understanding of how to construct and configure a [`Optimizer`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.Optimizer) and [`Scheduler`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.scheduler.Scheduler) inside a [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) instance. ## What’s next? To learn more about how to configure checkpointing behaviour using the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html), see Model Zoo Trainer - Checkpoint. ## Further Reading To learn about how you can configure a [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) instance using a YAML configuration file, you can check out: * Trainer YAML Overview To learn more about how you can use the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) in some core workflows, you can check out: * [Pretraining with Upstream Validation](../../../model-zoo/core-workflows/pretraining-with-upstream-validation) To learn more about how you can extend the capabilities of the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) class, you can check out: * [Defer Weight Initialization](../../../model-zoo/components/trainer-components/defer-weight-initialization) * [Numeric Precision](../../../model-zoo/components/trainer-components/numeric-precision) * [Train a model with weight sparsity](../../../model-zoo/tutorials/train-a-model-with-weight-sparsity) * [Checkpointing](../../../model-zoo/components/trainer-components/checkpointing) * [Customizing the Trainer with Callbacks](../../../model-zoo/components/trainer-components/customizing-the-trainer-with-callbacks) * [Logging](../../../model-zoo/components/trainer-components/logging) # Performance Flags Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/trainer-components/performance-flags The Cerebras PyTorch API provides a set of performance and debugging related flags. See [Performance/Debug Flags](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cstorch-backends) for a comprehensive list of the flags that are available. On this page we will cover how you can set these performance flags using the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) class. ## Prerequisites Make sure to have read through [Trainer Overview](../../../model-zoo/trainer-overview) and [Trainer Configuration Overview](../../../model-zoo/trainer-configuration-overview) which provide the basic overview of how to run Model Zoo models. In this document, you will be using the tools and configurations outlined in those pages. ## Scoped Flags While you can simply set the flags directly via the Cerebras PyTorch API, it is often the case that you want different flags for say training versus validation. As such, we provide two callbacks to facilitate this: * [`ScopedTrainFlags`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#cerebras.modelzoo.trainer.callbacks.Precision) * [`ScopedValidateFlags`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#cerebras.modelzoo.trainer.callbacks.Precision) With these callbacks, you can set different performance flags for training and validation. For example, one of the most important flags that you may want to set is the micro batch size (see working\_with\_microbatches for more details on micro batching). While you could set it globally by setting the [`cerebras.pytorch.backends.csx.performance.micro_batch_size`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.backends.csx.performance.micro_batch_size) flag, if you want to set different micro batch sizes for training and validation, you can set the values as follows. ```yaml YAML theme={null} trainer: init: ... callbacks: - ScopedTrainFlags: csx.performance.micro\_batch\_size: auto - ScopedValidateFlags: csx.performance.micro\_batch\_size: 2 ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ( ScopedTrainFlags, ScopedValidateFlags, ) trainer = Trainer( ..., callbacks=[ ScopedTrainFlags( **{ "csx.performance.micro_batch_size": "auto", } ), ScopedValidateFlags( **{ "csx.performance.micro_batch_size": 2, } ), ] ) ... ``` ## Conclusion Setting performance flags in the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) is a crucial step to optimize and debug your model training and validation processes. By leveraging the `ScopedTrainFlags` and `ScopedValidateFlags` callbacks, you can fine-tune your settings to cater to different stages of your workflow, such as assigning distinct micro batch sizes for training and validation. This flexibility allows for a more tailored and efficient training process, ensuring that you can maximize the performance of Model Zoo models. ## Further Reading To learn more about how you can extend the capabilities of the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) class, you can check out: * [Defer Weight Initialization](../../../model-zoo/trainer-configuration-overview)) * [Train a model with weight sparsity](../../../cs-torch/cerebras-pytorch-api/cerebras-pytorch-sparse) * [Checkpointing](../../../model-zoo/components/trainer-components/checkpointing) * [Customizing the Trainer with Callbacks](../../../model-zoo/components/trainer-components/customizing-the-trainer-with-callbacks) * [Logging](../../../model-zoo/components/trainer-components/logging) # Reproducibility Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/components/trainer-components/reproducibility Reproducibility is an essential component of training ML models. The [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) class features a way to enable determinism across runs, if so desired. On this page, you will learn how to configure the Trainer to ensure reproducibility. ## Prerequisites Make sure to have read through [Trainer Overview](../../../model-zoo/trainer-overview) and [Trainer Configuration Overview](../../../model-zoo/trainer-configuration-overview) which provide the basic overview of how to run Model Zoo models. In this document, you will be using the tools and configurations outlined in those pages. Trainer Seed The [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) supports configuring reproducibility by piggybacking off of [torch seed](https://pytorch.org/docs/stable/generated/torch.manual_seed.html) settings. While it is possible to manually set the torch seed outside of the Trainer class, it is strongly recommended to use the `seed` argument of the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) class to handle that for you. The following example shows how you can set the seed to 1234: ```yaml YAML theme={null} trainer: init: ... seed: 1234 ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer trainer = Trainer( ..., seed=1234, ) ... ``` > [!NOTE] > > If the seed is not provided or is **None** (the default value), determinism across runs is not ensured. > [!NOTE] > > [Torch modules](https://pytorch.org/docs/stable/generated/torch.nn.Module.html) initialize their weights upon instantiation. Setting the seed after a Module has already been instantiated may not necessarily ensure determinism. To avoid this pitfall, instead of passing an already-constructed model instance to the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) class, you should pass a callable that returns a torch Module. The Trainer will set the seed before invoking the callback, thus ensuring reproducibility. This is in line with deferred weight initialization, as described in [Defer Weight Initialization](../../../model-zoo/components/trainer-components/defer-weight-initialization). For a given run, the seed settings may affect any of the following: * The order of input data; * The global seed captured in the graph which may affect the values generated by random ops in the model; * The compile hash. For example, a model that has a random op, such as Dropout, may have a different compile hash for different seed settings. To avoid unnecessary recompiles, make sure to set the trainer seed. ## Conclusion Ensuring reproducibility in ML model training is crucial for consistency and reliability of results. By leveraging the `seed` argument in the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) class, you can achieve deterministic behavior across runs. This guide has provided step-by-step instructions on configuring the Trainer for reproducibility using both YAML and Python. ## Further Reading To learn more about how you can extend the capabilities of the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) class, you can check out: * [Defer Weight Initialization](../../../model-zoo/components/trainer-components/defer-weight-initialization) * [Train a model with weight sparsity](../../../model-zoo/tutorials/train-a-model-with-weight-sparsity) * [Checkpointing](../../../model-zoo/components/trainer-components/checkpointing) * [Customizing the Trainer with Callbacks](../../../model-zoo/components/trainer-components/customizing-the-trainer-with-callbacks) * [Logging](../../../model-zoo/components/trainer-components/logging) # Downstream Validation Using Bigcode Eval Harness Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/core-workflows/downstream-validation-using-bigcode-eval-harness This page walks through the steps for performing downstream validation on the Cerebras Wafer-Scale cluster using [BigCode’s Evaluation Harness](https://github.com/bigcode-project/bigcode-evaluation-harness) (BCEH). BCEH is a framework for evaluating code generation models. While you can configure BCEH as part of your training (see [Pretraining with Downstream Validation](../../model-zoo/core-workflows/pretraining-with-downstream-validation) from the Cerebras Model Zoo. The examples in this guide will perform downstream validation on [LLaMA3 8B](https://huggingface.co/meta-llama/Meta-Llama-3-8B). By the end of this guide, you will be able to leverage the BCEH framework to perform standalone downstream validation on your models on CS-X. ## Prerequisites Please ensure that you have installed the Cerebras Model Zoo package by going through the installation guide. Note that BCEH version tested and packaged in the Cerebras Model Zoo is the pinned to [this commit](https://github.com/bigcode-project/bigcode-evaluation-harness/tree/84b96da31b7f840b55c5733325346176140cdb6b). Please also read through the [Trainer Overview](../model-zoo/trainer-overview) and [Trainer Configuration Overview](../../model-zoo/trainer-configuration-overview)), as these guides will help understand how we configure running BCEH standalone. > [!NOTE] > > This guide configures the downstream BCEH run using V2 YAML. While release 2.3 includes support for legacy V1 YAML, please convert the configuration to V2 using `convert_legacy_params_to_trainer_params` from the script `src/cerebras/modelzoo/trainer/utils.py`. ## Configure the Run This section covers the required steps for setting up an BCEH run to perform standalone downstream validation on code generation tasks. In particular, you will need to write a YAML configuration file to configure an instance of the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) callback. The example in this section configure code evaluation on the bigcode eval harness task `humaneval` using a single CSX. If you aren’t interested in seeing the break down of the configuration, feel free to skip ahead to the [Putting it All Together](#wsc-modelzoo-bceh-pretrain-full-yaml) section to see the full YAML configuration. ### Configure the CSX Backend The first step is to specify the CSX backend and resources required for the run. Please create a YAML configuration file with the following cluster config: ```yaml theme={null} trainer: init: backend: backend_type: CSX cluster_config: num_csx: 1 ``` This example uses a single CSX, but you can readily update `num_csx` to run BCEH on multiple CSXs for improved performance. ### Configure the Model > [!NOTE] > > Starting from release 2.4.0, specifying `model_name` is now deprecated and replaced with `name`. Next, please add the following model configuration in the YAML for [LLaMA3 8B](https://huggingface.co/meta-llama/Meta-Llama-3-8B) with 8K context length: ```yaml theme={null} trainer: init: backend: # CSX ... model: name: llama # This setting is required # Embedding vocab_size: 128256 hidden_size: 4096 position_embedding_type: "rotary" pos_scaling_factor: 1.0 rope_theta: 500000.0 rotary_dim: 128 share_embedding_weights: false max_position_embeddings: 8192 embedding_dropout_rate: 0.0 embedding_layer_norm: false # Decoder num_hidden_layers: 32 dropout_rate: 0.0 layer_norm_epsilon: 1.0e-5 norm_type: "rmsnorm" # Decoder - Attention num_heads: 32 attention_type: "scaled_dot_product" attention_module: "multiquery_attention" attention_dropout_rate: 0.0 use_projection_bias_in_attention: false use_ffn_bias_in_attention: false extra_attention_params: num_kv_groups: 8 # Decoder - ffn filter_size: 14336 nonlinearity: "swiglu" use_ffn_bias: false # Task-specific use_bias_in_output: false loss_scaling: "num_tokens" loss_weight: 1.0 # Initializer initializer_range: 0.02 ``` > [!NOTE] > > To run downstream validation harness, you must specify the `name` setting in the model configuration. Valid names corresponding to the supported models include: > > * `btlm` > > * `bloom` > > * `gpt2` > > * `gptj` > > * `falcon` > > * `gpt3` > > * `gpt-neox` > > * `llama` > > * `mistral` > > * `mpt` > > * `jais` > > * `santacoder` > > * `starcoder` ### Configure the BCEH Callback BCEH is implemented as an extension to the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) callback. Add the following configuration for the `BigCodeEvalHarness` callback. ```yaml theme={null} trainer: init: backend: # CSX ... model: # Llama3-8B name: llama # This setting is required ... callbacks: - BigCodeEvalHarness: # BigCode Eval Harness settings (exposed via CLI) bigcode_args: tasks: humaneval # CSX-specific eval harness settings (exposed via CLI) keep_data_dir: false hf_cache_dir: # Dataloader settings batch_size: 4 shuffle: false max_sequence_length: 8192 num_workers: 1 data_dir: tokenizer_file_path: eos_id: 128001 pretrained_model_name_or_path: null ``` The `bigcode_args` section exposes the following settings configure the BCEH run: | BigCode Eval Harness CLI Arguments | Description | | - | - | | `--prefix` | Number of examples to be added to the fewshot context string. Defaults to 0 | | `--temperature` | Sampling temperature used for generation. | | `--top_p` | Top-p parameter used for nucleus sampling. | | `--top_k` | Top-k parameter used for generation. | | `--n_samples` | Number of completions to generate for each sample. Defaults to 1. | | `--seed` | Random seed used for evaluation. | | `--tasks` | Comma separated string specifying BigCode Eval Harness tasks. | | `--instruction_tokens` | A series of instruction tokens used for instruction-tuning benchamrks separated by comma e.g. \,\,\ | | `--max_length_generation` | Maximum length of generated sequence (prompt+generation). | | `--limit` | Number of samples to solve and evaluate from the benchmark. | | `--limit_start` | Optional offset to start from when limiting the number of samples. | | `--save_every_k_tasks` | Optional saving after every k tasks. | | `--load_generations_path` | Path of file with previously generated solutions, if provided generation is skipped and only evaluation is done | | `--load_data_path` | Path of additional data to load for the tasks. | | `--metric_output_path` | Path to save the results. | | `--load_generations_intermediate_paths` | List of paths for saving the intermediate code generations. | | `--save_generations_path` | Path for saving the model’s output code generations. | | `--save_references_path` | Path for saving the references solutions/tests. | | `--prompt` | Prompt type to use for generation in HumanEvalPack tasks. | | `--check_references` | Don’t run generation but benchmark groundtruth (useful for debugging). | You can either specify the settings here or pass them via CLI arguments to the standalone BCEH run script. The callback configuration accepts dataloader settings that you must specify in the YAML to set up input data preprocessing for the run: | DataLoader Settings | Description | | - | - | | `data_dir` | This setting is required. Provide a path to the mounted directory visible to the worker containers where eval harness task data samples are dumped after preprocessing. Use the `mount_dirs` argument to specify a dir mount, similar to our existing flows. | | `tokenizer_file_path` | Path to a custom tokenizer (JSON) file. If you provide a custom tokenizer, then you must also specify `eos_id`; otherwise, you must provide a pretrained tokenizer from Hugging Face in `pretrained_model_name_or_path`. | | `pretrained_model_name_or_path` | Hugging Face (HF) pretrained model name or path. This setting is required if you do not specify `tokenizer_file_path`. For detailed description, see [HF AutoTokenizers](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoTokenizer.from_pretrained.pretrained_model_name_or_path). | | `eos_id` | End-of-sentence (eos) token ID to signal the termination of a sequence. This setting is required if you specify a custom tokenizer in `tokenizer_file_path`. You can set this by looking for the ID corresponding to the eos token in the custom tokenizer JSON file. | | `max_sequence_length` | Maximum length of the input sequence. This setting is required for preprocessing input data samples from the specified eval harness tasks. You should align the `max_sequence_length` field to the `max_position_embeddings` value in the model configuration of the YAML. If you don’t specify `max_sequence_length`, the flow defaults to this `max_position_embeddings` setting. | Additionally, you may optionally specify the following, CSX-specific eval harness setting: * `keep_data_dir`: Use this to preserve the preprocessed eval harness task data samples, i.e. the directory specified under `data_dir`. Defaults to False, i.e. data samples are deleted after the run. ### (Optional) Configure HuggingFace (HF) Cache Directory BCEH utilizes HF’s APIs to download task data and other configurations. This data is by default cached under `$HOME/.cache/huggingface`. However, you may choose to specify a different directory for this cached data via the [`HFCacheDir`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) callback: ```yaml theme={null} trainer: init: backend: # CSX ... model: # Llama3-8B ... callbacks: - BigCodeEvalHarness: ... - HFCacheDir: cache_dir: ``` ### Configure Generation Settings All BCEH tasks are generative (autoregressive) in nature. In order to run generative inference on CSX, you must specify the following inference settings in the model config of YAML file: * `start_token` - ID of the special token that indicates where to start inferring for each sample, as described above. You may specify a list of token IDs instead of a single ID. If you do, the model will start inference at the first token that matches any one of the provided IDs. The model will pad inferred predictions with the first ID in the list. * `stop_sequences` - List of sequences (each one being a list of token IDs). If any one of these sequences is emitted by the model, inference will stop for that sample. For example, suppose you would like to stop inferring after either a newline character (e.g. token id 1), or a combination of a period (e.g. token id 2) followed by a space (e.g. token id 3). In this case, set stop\_sequences to \[\[1], \[2, 3]]. To stop inferring after seeing a newline character only, set stop\_sequences to \[\[1]]. To disable this feature, set `stop_sequences` to an empty list \[]. Additionally, the following optional parameters may be set: * `max_tokens` - Maximum tokens to infer for each sample. * `loop_dim` - Indicates the sequence dimension in the input and output data. Default value is 1. If set to 0, indicates that both input and output data is transposed (i.e. `sequence X samples` instead of `samples X sequence`). Please update the YAML file to add these inference settings: ```yaml theme={null} trainer: init: backend: # CSX ... model: # Llama3-8B name: llama ... # Inference Settings start_token: 128256 # Set to `vocab_size` stop_sequences: [] # Left empty as stop_sequences are overridden from the BCEH task max_tokens: 256 # Default from HF implementations loop_dim: 1 callbacks: - BigCodeEvalHarness: # BigCode Eval Harness settings bigcode_args: tasks: humaneval ... ... ``` > [!NOTE] > > 1. For `start_token`, it is ideal to choose a value that’s not going to be generated by the model, i.e. `vocab_size` in the example above. > > 2. The code generation task itself defines `stop_sequences`. For instance, see the specification of stop tokens for [humaneval](https://github.com/bigcode-project/bigcode-evaluation-harness/blob/334efb7feb1c6d18fc4be2c71ae73248f3de8440/bigcode_eval/tasks/humaneval.py#L52) . The flow will internally override the `stop_sequences` config with the value from the task, so you can also specify an arbitrary, valid value in the YAML as shown above. ### Putting it All Together Here’s what the full YAML configuration looks like once you follow this guide for configuring the individual pieces: ```yaml theme={null} trainer: init: backend: # CSX backend_type: CSX cluster_config: num_csx: 1 model: name: llama # This setting is required # Embedding vocab_size: 128256 hidden_size: 4096 position_embedding_type: "rotary" pos_scaling_factor: 1.0 rope_theta: 500000.0 rotary_dim: 128 share_embedding_weights: false max_position_embeddings: 8192 embedding_dropout_rate: 0.0 embedding_layer_norm: false # Decoder num_hidden_layers: 32 dropout_rate: 0.0 layer_norm_epsilon: 1.0e-5 norm_type: "rmsnorm" # Decoder - Attention num_heads: 32 attention_type: "scaled_dot_product" attention_module: "multiquery_attention" attention_dropout_rate: 0.0 use_projection_bias_in_attention: false use_ffn_bias_in_attention: false extra_attention_params: num_kv_groups: 8 # Decoder - ffn filter_size: 14336 nonlinearity: "swiglu" use_ffn_bias: false # Task-specific use_bias_in_output: false loss_scaling: "num_tokens" loss_weight: 1.0 # Initializer initializer_range: 0.02 # Inference Settings start_token: 128256 # Set to `vocab_size` stop_sequences: [] # Left empty as stop_sequences are overridden from the BCEH task max_tokens: 256 # Default from HF implementations loop_dim: 1 callbacks: - BigCodeEvalHarness: # BigCode Eval Harness settings (exposed via CLI) bigcode_args: tasks: humaneval # CSX-specific eval harness settings (exposed via CLI) keep_data_dir: false hf_cache_dir: # Dataloader settings batch_size: 4 shuffle: false max_sequence_length: 8192 num_workers: 1 data_dir: tokenizer_file_path: eos_id: 128001 pretrained_model_name_or_path: null ``` ## Running BCEH on CS-X Once the YAML configuration is complete, use the Model Zoo CLI to run standalone BCEH: ```bash theme={null} cszoo bigcode_eval --help usage: cszoo bigcode_eval [-h] [--prefix PREFIX] [--max_tokens MAX_TOKENS] [--temperature TEMPERATURE] [--top_p TOP_P] [--top_k TOP_K] [--n_samples N_SAMPLES] [--seed SEED] [--tasks task1,task2] [--instruction_tokens INSTRUCTION_TOKENS] [--limit LIMIT] [--limit_start LIMIT_START] [--save_every_k_tasks SAVE_EVERY_K_TASKS] [--load_generations_path LOAD_GENERATIONS_PATH] [--load_data_path LOAD_DATA_PATH] [--metric_output_path METRIC_OUTPUT_PATH] [--load_generations_intermediate_paths [LOAD_GENERATIONS_INTERMEDIATE_PATHS [LOAD_GENERATIONS_INTERMEDIATE_PATHS ...]]] [--save_generations_path SAVE_GENERATIONS_PATH] [--save_references_path SAVE_REFERENCES_PATH] [--prompt PROMPT] [--check_references] [--keep_data_dir] [--target_device {CSX}] [-o MODEL_DIR] [--checkpoint_path CHECKPOINT_PATH] [--load_checkpoint_states LOAD_CHECKPOINT_STATES] [--logging LOGGING] [--compile_only] [--validate_only] [--job_labels JOB_LABELS [JOB_LABELS ...]] [--job_priority {p1,p2,p3}] [--mount_dirs MOUNT_DIRS [MOUNT_DIRS ...]] [--python_paths PYTHON_PATHS [PYTHON_PATHS ...]] [--credentials_path CREDENTIALS_PATH] [--mgmt_address MGMT_ADDRESS] [--disable_version_check] [--num_csx NUM_CSX] [--debug_args [DEBUG_ARGS [DEBUG_ARGS ...]]] [--debug_args_path DEBUG_ARGS_PATH] [--ini [INI [INI ...]]] [--transfer_processes TRANSFER_PROCESSES] [--config CONFIG] params ``` > [!NOTE] > > 1. We support only a subset of BigCode’s [command line interface (CLI) arguments](https://github.com/bigcode-project/bigcode-evaluation-harness/blob/main/main.py) as listed above. > > 2. You may also specify these arguments in the YAML under the `bigcode_args` key of the `BigCodeEvalHarness` configuration, but please note that the CLI setting will override the settings in the YAML. > > 3. The `params` argument is required. Use it to specify the path to the YAML configuration file. > > 4. Use the `--checkpoint_path` CLI argument to specify the path to the checkpoint file to load model weights from. If a checkpoint path is not provided, we support checkpoint autoloading in this flow such that the latest checkpoint file will be picked up from the specified `model_dir`. ### Code Generation on CSX We only support BCEH’s generation-only flow to generate model outputs and dump these generations to JSON files. Use the `--save_generations_path` argument to specify the path for saving the generations. If no absolute path is provided, the generations will be dumped inside of `model_dir`. The code execution and evaluation flow is run on CPU, preferably in a sandboxed environment, using these dumped model outputs. ### Example Let’s assume that the YAML configuration file above is written to `./llama3_8B_bceh.yaml`. Then, to run code generation for task `humaneval` set up a bash script as follows: ```bash theme={null} cszoo bigcode_eval \ --target_device CSX \ --params ./llama3_8B_bceh.yaml \ --checkpoint_path \ --python_paths \ --mount_dirs ``` By default, the model will perform greedy sampling of the inferred tokens, i.e. for all of the model’s outputs, pick the token with the highest probability. In order to perform non-greedy sampling, you can pass in values for `temperature`, `top_k` or `top_p` sampling to either the bash script or under `bigcode_args` of the YAML. For example: ```bash theme={null} cszoo bigcode_eval \ --target_device CSX \ --params ./llama3_8B_bceh.yaml \ --checkpoint_path \ --python_paths \ --mount_dirs \ --temperature 0.7 \ --top_k 10 \ --top_p 0.95 ``` ### Code Execution and Evaluation on CPU To obtain the final eval scores, please clone [BigCode’s official repository](https://github.com/bigcode-project/bigcode-evaluation-harness/tree/main). Some BigCode tasks, such as `humaneval`, require executing the model’s generated code for processing the final eval scores. Thus, for security purposes, use the instructions [here](https://github.com/bigcode-project/bigcode-evaluation-harness/tree/main?tab=readme-ov-file#evaluation-only) to set up a containerized environment. Finally, to obtain the final eval scores, invoke the BCEH’s main script using the `--load_generations_path` CLI argument. ### Example Output Please make note of the path of the model’s output generations in the logs, i.e. `/20240627_051131/bigcode_0/generations_humaneval_1.json`. Set up a bash script as follows to invoke the BCEH script: ```bash theme={null} cszoo bigcode_eval \ --tasks humaneval \ --check_references \ --load_generations_path /20240627_051131/bigcode_0/generations_humaneval_1.json \ --metric_output_path ./evaluation_results.json \ --params ``` The final code eval results will be saved in file `./evaluation_results.json` are as follows: ```json theme={null} ... { "humaneval": { "pass@1": 0.13414634146341464 }, "config": { "prefix": "", "do_sample": true, "temperature": 0.2, "top_k": 0, "top_p": 0.95, "n_samples": 1, "eos": "<|endoftext|>", "seed": 0, "model": "codeparrot/codeparrot-small", "modeltype": "causal", "peft_model": null, "revision": null, "use_auth_token": false, "trust_remote_code": false, "tasks": "humaneval", "instruction_tokens": null, "batch_size": 1, "max_length_generation": 512, "precision": "fp32", "load_in_8bit": false, "load_in_4bit": false, "left_padding": false, "limit": null, "limit_start": 0, "save_every_k_tasks": -1, "postprocess": true, "allow_code_execution": true, "generation_only": false, "load_generations_path": "/20240627_051131/bigcode_0/generations_humaneval_1.json", "load_data_path": null, "metric_output_path": "evaluation_results.json", "save_generations": false, "load_generations_intermediate_paths": null, "save_generations_path": "generations.json", "save_references": false, "save_references_path": "references.json", "prompt": "prompt", "max_memory_per_gpu": null, "check_references": false } } ``` > [!NOTE] > > 1. The `config` section of the final output JSON contains all the default values from BigCode’s [CLI](https://github.com/bigcode-project/bigcode-evaluation-harness/blob/main/main.py). Feel free to ignore this section and consider only the final eval score, i.e. `"pass@1": 0.13414634146341464` above. > > 2. Please ensure that `--check_references` is set for tasks that require code execution. > > 3. Setting up a sandboxed environment to run code executions is optional. > > 4. Please ensure that the `--tasks` argument specifies the correct task for which you produced the model’s output generations on CSX, i.e. `humaneval` in the example above. ### Run Multiple Generative Tasks You can run multiple tasks by configuring multiple [`BigCodeEvalHarness`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) callbacks (one per task) in the YAML. For example, you may update the YAML config as such to run downstream validation on generative tasks `mpbb` and `humaneval`: ```yaml theme={null} trainer: init: backend: # CSX ... model: # Llama3-8B name: llama # This setting is required ... # Inference Settings start_token: 128256 # Set to `vocab_size` stop_sequences: [] # Arbitrary value that will be overridden from the task spec max_tokens: 256 # Default from HF implementations loop_dim: 1 callbacks: - BigCodeEvalHarness: # BigCode Eval Harness settings (exposed via CLI) bceh_args: tasks: humaneval, mbpp # CSX-specific eval harness settings (exposed via CLI) keep_data_dir: false hf_cache_dir: # Dataloader settings batch_size: 4 shuffle: false max_sequence_length: 8192 num_workers: 1 data_dir: tokenizer_file_path: eos_id: 128001 pretrained_model_name_or_path: null ``` ## Supported Tasks * You may perform downstream validation on all BCEH tasks except for `DS1000`, since it requires Python version 3.7.10, but we support 3.8.0 in our packaged environment. ## Adding New Tasks Please refer to BigCode’s new task implementation guide [here](https://github.com/bigcode-project/bigcode-evaluation-harness/blob/main/docs/guide.md) to add new tasks. ## Limitations * You may only specify running a single generative task at a time. You should configure multiple BCEH tasks via separate callbacks, as shown above. * We only support the generation flow for BCEH. In order to run the code execution and evalution flow, please create a separate clone of the BCEH repository to obtain the final eval scores using the outputs generated on CSX. * Please turn on grad accumulation and choose a small micro batch size (between 16 to 32) under the `flags` configuration of the `BigCodeEvalHarness` callback of the YAML. ## Conclusion In summary, by following this guide you have run standalone downstream validation for the Llama3-8B model on BCEH’s task `humaneval`. You should now be comfortable in configuring more downstream BCEH runs on your model of choice on even more code eval tasks. ## What’s next? To run downstream validation on general eval datasets and tasks, please see check out: * [Downstream Validation using Eleuther Eval Harness](../../model-zoo/core-workflows/downstream-validation-using-eleuther-eval-harness) You can also perform downstream validation using BCEH as part of your pretraining runs with upstream validation. Check out the following guide: * [Pretraining with Downstream Validation](../../model-zoo/core-workflows/downstream-validation-using-eleuther-eval-harness) # Downstream Validation Using Eleuther Eval Harness Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/core-workflows/downstream-validation-using-eleuther-eval-harness Learn how to run downstream validation using EleutherAI’s Evaluation Harness (EEH). [EleutherAI’s Evaluation Harness](https://github.com/EleutherAI/lm-evaluation-harness/tree/v0.4.7) (EEH) is a popular framework for evaluating large language models across various different datasets and tasks. You can configure EEH as part of your training workflow. See [Pretraining with Downstream Validation](../../model-zoo/core-workflows/pretraining-with-downstream-validation). The examples in this guide will perform downstream validation on [LLaMA3 8B](https://huggingface.co/meta-llama/Meta-Llama-3-8B). ## Prerequisites Please ensure that you have installed the Cerebras Model Zoo package by going through the installation guide. Note that EEH version tested and packaged in the Cerebras Model Zoo is the official release [v0.4.7](https://github.com/EleutherAI/lm-evaluation-harness/tree/v0.4.7). Please also read through the [Trainer Overview](../../model-zoo/trainer-overview) and [Trainer Configuration Overview](../../model-zoo/trainer-configuration-overview), as these guides will help understand how to configure running EEH standalone. ## Configure the Run This section covers the required steps for setting up an EEH run to perform standalone downstream validation on various tasks. In particular, you will need to write a YAML configuration file to configure an instance of the [`Trainer`](../../model-zoo/trainer-overview) callback. The example in this section configures evaluation for `LLaMA3 8B` via the multiple choice (non-generative) eval harness task `winogrande` using a single CSX. If you aren’t interested in seeing the break down of the configuration, feel free to skip ahead to the [Putting it All Together](#putting-it-all-together) section to see the full YAML configuration. ### Configure the CSX Backend The first step is to specify the CSX backend and resources required for the run. Create a YAML configuration file with the following cluster config: ```yaml theme={null} trainer: init: backend: backend_type: CSX cluster_config: num_csx: 1 ``` This example uses a single CSX, but you can readily update `num_csx` to run EEH on multiple CSXs for improved performance. ### Configure the Model Next, please add the following model configuration in the YAML for [LLaMA3 8B](https://huggingface.co/meta-llama/Meta-Llama-3-8B) with 8K context length: ```yaml theme={null} trainer: init: backend: # CSX ... model: name: llama # This setting is required # Embedding vocab_size: 128256 hidden_size: 4096 position_embedding_type: "rotary" pos_scaling_factor: 1.0 rope_theta: 500000.0 rotary_dim: 128 share_embedding_weights: false max_position_embeddings: 8192 embedding_dropout_rate: 0.0 embedding_layer_norm: false # Decoder num_hidden_layers: 32 dropout_rate: 0.0 layer_norm_epsilon: 1.0e-5 norm_type: "rmsnorm" # Decoder - Attention num_heads: 32 attention_type: "scaled_dot_product" attention_module: "multiquery_attention" attention_dropout_rate: 0.0 use_projection_bias_in_attention: false use_ffn_bias_in_attention: false extra_attention_params: num_kv_groups: 8 # Decoder - ffn filter_size: 14336 nonlinearity: "swiglu" use_ffn_bias: false # Task-specific use_bias_in_output: false loss_scaling: "num_tokens" loss_weight: 1.0 # Initializer initializer_range: 0.02 ``` > [!NOTE] > > To run downstream validation harness, you must specify the `name` setting in the model configuration. Valid names corresponding to the supported models include: > > * `btlm` > > * `bloom` > > * `gpt2` > > * `gptj` > > * `falcon` > > * `gpt3` > > * `gpt-neox` > > * `llama` > > * `mistral` > > * `mpt` > > * `jais` > > * `santacoder` > > * `starcoder` ### Configure the EEH Callback EEH is implemented as an extension to the [`Trainer`](../../model-zoo/trainer-overview) callback. Add the following section in the YAML to set up the [`EleutherEvalHarness`](../../model-zoo/core-workflows/downstream-validation-using-eleuther-eval-harness) callback: ```yaml theme={null} trainer: init: backend: # CSX ... model: # Llama3-8B name: llama # This setting is required ... callbacks: - EleutherEvalHarness: # Eleuther Eval Harness settings (also exposed via CLI) eeh_args: tasks: winogrande num_fewshot: 0 # CSX-specific eval harness settings (also exposed via CLI) keep_data_dir: false # Dataloader settings batch_size: 4 shuffle: false max_sequence_length: 8192 num_workers: 1 data_dir: tokenizer_file_path: eos_id: 128001 pretrained_model_name_or_path: null # Eval Harness Flags flags: csx.performance.micro_batch_size: null ``` The `eeh_args` section exposes the following settings to configure the EEH run: | Eleuther Eval Harness CLI Arguments | Description | | - | - | | `--tasks` | Comma separated string specifying Eleuther Eval Harness tasks. To get full list of tasks, use the command `lm-eval --tasks list` from within your python venv. | | `--num_fewshot` | Number of examples to be added to the fewshot context string. Defaults to 0 | | `--output_path` | The path to the output file where the result metrics will be saved. If the path is a directory and log\_samples is true, the results will be saved in the directory. Else the parent directory will be used. | | `--limit` | Accepts an integer, or a float between 0.0 and 1.0. This limits the number of documents to evaluate per task to the first X documents (if an integer) or first X% of documents. This is useful for debugging. | | `--use_cache` | A path to a sqlite db file for caching model responses. None if not caching. | | `--cache_requests {true,refresh,delete}` | Speed up evaluation by caching the building of dataset requests. None if not caching. | | `--check_integrity` | Whether to run the relevant part of the test suite for the tasks. | | `--write_out` | Prints the prompt for the first few documents. Defaults to False. | | `--log_samples` | If True, write out all model outputs and documents for per-sample measurement and post-hoc analysis. Defaults to False. | | `--show_config` | If True, shows the the full config of all tasks at the end of the evaluation. Defaults to False. | | `--include_path` | Additional path to include if there are external tasks to include. | | `--predict_only` | Use with –log\_samples. Only model outputs will be saved and metrics will not be evaluated. | | `--seed` | Set seed for python’s random, numpy and torch. | | `--temperature` | Sampling temperature used for generation (autoregressive, generate\_until tasks only). | | `--top_p` | Top-p parameter used for nucleus sampling (autoregressive, generate\_until tasks only). | | `--top_k` | Top-k parameter used for generation (autoregressive, generate\_until tasks only). | You can either specify the settings here or pass them via CLI arguments to the standalone EEH run script. The callback configuration also accepts dataloader settings that you must specify in the YAML to set up input data preprocessing for the run: | DataLoader Settings | Description | | - | - | | `data_dir` | This setting is required. Provide a path to the mounted directory visible to the worker containers where eval harness task data samples are dumped after preprocessing. Use the `mount_dirs` argument to specify a dir mount, similar to our existing flows. | | `tokenizer_file_path` | Path to a custom tokenizer (JSON) file. If you provide a custom tokenizer, then you must also specify `eos_id`; otherwise, you must provide a pretrained tokenizer from Hugging Face in `pretrained_model_name_or_path`. | | `pretrained_model_name_or_path` | Hugging Face (HF) pretrained model name or path. This setting is required if you do not specify `tokenizer_file_path`. For detailed description, see [HF AutoTokenizers](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoTokenizer.from_pretrained.pretrained_model_name_or_path). | | `eos_id` | End-of-sentence (eos) token ID to signal the termination of a sequence. This setting is required if you specify a custom tokenizer in `tokenizer_file_path`. You can set this by looking for the ID corresponding to the eos token in the custom tokenizer JSON file. | | `max_sequence_length` | Maximum length of the input sequence. This setting is required for preprocessing input data samples from the specified eval harness tasks. You should align the `max_sequence_length` field to the `max_position_embeddings` value in the model configuration of the YAML. If you don’t specify `max_sequence_length`, the flow defaults to this `max_position_embeddings` setting. | Additionally, you may optionally specify the following, CSX-specific eval harness setting: * `keep_data_dir`: Use this to preserve the preprocessed eval harness task data samples, i.e. the directory specified under `data_dir`. Defaults to False, i.e. data samples are deleted after the run. ### (Optional) Configure HuggingFace (HF) Cache Directory EEH utilizes HF’s APIs to download task data and other configurations. This data is by default cached under `$HOME/.cache/huggingface`. However, you may choose to specify a different directory for this cached data via the [`HFCacheDir`](../model-zoo/api/cerebras-modelzoo/cerebras-modelzoo) callback: ```yaml theme={null} trainer: init: backend: # CSX ... model: # Llama3-8B ... callbacks: - EleutherEvalHarness: ... - HFCacheDir: cache_dir: ``` ### Putting it All Together Here’s what the full YAML configuration looks like once you follow this guide for configuring the individual pieces: ```yaml theme={null} trainer: init: backend: backend_type: CSX cluster_config: num_csx: 1 mount_dirs: model: name: llama # Embedding vocab_size: 128256 hidden_size: 4096 position_embedding_type: "rotary" pos_scaling_factor: 1.0 rope_theta: 500000.0 rotary_dim: 128 share_embedding_weights: false max_position_embeddings: 8192 embedding_dropout_rate: 0.0 embedding_layer_norm: false # Decoder num_hidden_layers: 32 dropout_rate: 0.0 layer_norm_epsilon: 1.0e-5 norm_type: "rmsnorm" # Decoder - Attention num_heads: 32 attention_type: "scaled_dot_product" attention_module: "multiquery_attention" attention_dropout_rate: 0.0 use_projection_bias_in_attention: false use_ffn_bias_in_attention: false extra_attention_params: num_kv_groups: 8 # Decoder - ffn filter_size: 14336 nonlinearity: "swiglu" use_ffn_bias: false # Task-specific use_bias_in_output: false loss_scaling: "num_tokens" loss_weight: 1.0 # Initializer initializer_range: 0.02 callbacks: - EleutherEvalHarness: eeh_args: tasks: winogrande num_fewshot: 0 keep_data_dir: false # Dataloader settings batch_size: 4 shuffle: false max_sequence_length: 8192 num_workers: 1 data_dir: tokenizer_file_path: eos_id: 128001 pretrained_model_name_or_path: null # Eval Harness Flags flags: csx.performance.micro_batch_size: null ``` ## Running EEH on CS-X Now that the the YAML configuration is complete, use the [Model Zoo CLI](../../../rel-2.5.0/model-zoo/cli-overview) to run EEH on various tasks. This script accepts the following arguments: ```bash lm_eval [expandable] theme={null} cszoo lm_eval --help usage: cszoo lm_eval [-h] [--tasks task1,task2] [--num_fewshot N] [--output_path DIR|DIR/file.json] [--limit N|0: for cluster management. If None, the value from a pre-configured location will be used if available. Defaults to None. --disable_version_check Disable version check for local experimentation and debugging --num_csx NUM_CSX Number of CS nodes. Defaults to 1 --debug_args [DEBUG_ARGS [DEBUG_ARGS ...]] DebugArgs to pass to the Cerebras compile and execution, pass as --debug_args sub.object.key=value, where value can be bool int, float or str --debug_args_path DEBUG_ARGS_PATH Path to debugs args file. Defaults to None. --ini [INI [INI ...]] Debug INI settings to pass to the Cerebras compile and execution, pass as --ini key=value, where value can be bool, int, float or str --transfer_processes TRANSFER_PROCESSES Number of processes to use when transferring weights. --config CONFIG Specifies a specific key of the params file to return. Eleuther Eval Harness Arguments: --tasks task1,task2, -t task1,task2 Comma-separated list of task names or task groupings to evaluate on. To get full list of tasks, use one of the commands `lm-eval --tasks {{list_groups,list_subtasks,list_tags,list}}` to list out all available names for task groupings; only (sub)tasks; tags; or all of the above --num_fewshot N, -f N Number of examples in few-shot context --output_path DIR|DIR/file.json The path to the output file where the result metrics will be saved. If the path is a directory and log_samples is true, the results will be saved in the directory. Else the parent directory will be used. --limit N|0 [!NOTE] > > 1. We support a subset of Eleuther’s command line interface (CLI) arguments above. For a more detailed descrition of these supported arguments, see the [EEH documentation](https://github.com/EleutherAI/lm-evaluation-harness/blob/v0.4.7/docs/interface.md). > > 2. You may also specify these arguments in the YAML under the `eeh_args` key of the `EleutherEvalHarness` configuration, but please note that the CLI setting will override the settings in the YAML. > > 3. The `params` CLI argument is required. Use it to specify the path to the YAML configuration file. > > 4. Use the `--checkpoint_path` CLI argument to specify the path to the checkpoint file to load model weights from. If a checkpoint path is not provided, we support checkpoint autoloading in this flow such that the latest checkpoint file will be picked up from the specified `model_dir`. ## Supported Tasks * We support `lm_eval@v0.4.7 `. * You may perform downstream validation on all EEH tasks with `output_type: loglikelihood` or `output_type: multiple_choice` in the task specification. See [asdiv](https://github.com/EleutherAI/lm-evaluation-harness/blob/4600d6bf73ba2cf7037ae7feada03315839ef185/lm_eval/tasks/asdiv/default.yaml#L3) and [arc\_easy](https://github.com/EleutherAI/lm-evaluation-harness/blob/4600d6bf73ba2cf7037ae7feada03315839ef185/lm_eval/tasks/arc/arc_easy.yaml#L6) for respective examples. You may specify each of these types of tasks separately or together in a single [`EleutherEvalHarness`](../model-zoo/trainer-configuration-overview) callback. * We currently do not support eval harness tasks with `output_type: loglikelihood_rolling`. ## Adding New Tasks Please refer to Eleuther’s new task implementation guide [here](https://github.com/EleutherAI/lm-evaluation-harness/blob/v0.4.7/docs/new_task_guide.md) to add new tasks. ## Limitations * We currently do not support running multiple generative eval harness tasks in the same callback. * EEH task groups, such as [agieval](https://github.com/EleutherAI/lm-evaluation-harness/blob/v0.4.7/lm_eval/tasks/agieval/README.md), comprise multiple generative sub tasks that you will have to configure in the YAML via separate callbacks. * Please turn on grad accumulation and choose a small micro batch size (between 16 to 32) under the `flags` configuration of the `EleutherEvalHarness` callback of the YAML, ## Examples > [accordion] Single Non-generative Task > > Let’s assume that the YAML configuration file above is written to `./llama3_8B_eeh.yaml`. Then, to run evaluation for task `winogrande`, please set up a bash script as follows: > > ```bash theme={null} > cszoo lm_eval ./llama3_8B_eeh.yaml \ > --target_device CSX \ > --checkpoint_path \ > --python_paths \ > --mount_dirs \ > > ``` > > The output logs are as follows: > > ```bash theme={null} > ... > 2024-06-24 11:06:49,596 INFO: | EleutherAI Eval Device=CSX, GlobalStep=1, Batch=632, Rate=34.38 samples/sec, GlobalRate=34.34 samples/sec > 2024-06-24 11:06:49,625 INFO: | EleutherAI Eval Device=CSX, GlobalStep=1, Batch=633, Rate=34.39 samples/sec, GlobalRate=34.35 samples/sec > 2024-06-24 11:07:04,333 INFO: (None), gen_kwargs: ({'temperature': None, 'top_k': None, 'top_p': None, 'max_tokens': None}), limit: None, num_fewshot: None, batch_size: None > 2024-06-24 11:07:04,696 INFO: > | Tasks |Version|Filter|n-shot|Metric|Value | |Stderr| > |----------|------:|------|-----:|------|-----:|---|-----:| > |winogrande| 1|none | 0|acc |0.7284|± |0.0141| > ``` > [accordion] Multiple Non-generative Tasks > > To run evaluation on more non-generative tasks, you may update the run script to the following: > > ```bash theme={null} > cszoo lm_eval ./llama3_8B_eeh.yaml \ > --target_device CSX \ > --tasks arc_challenge,hellaswag,openbookqa,piqa,winogrande \ > --checkpoint_path \ > --python_paths \ > --mount_dirs \ > ``` > > The output logs are as follows: > > ```bash theme={null} > ... > 2024-06-24 12:40:44,896 INFO: | EleutherAI Eval Device=CSX, GlobalStep=1, Batch=2979, Rate=34.40 samples/sec, GlobalRate=34.39 samples/sec > 2024-06-24 12:40:57,106 INFO: | EleutherAI Eval Device=CSX, GlobalStep=1, Batch=2980, Rate=34.40 samples/sec, GlobalRate=34.39 samples/sec > 2024-06-24 12:41:10,333 INFO: (None), gen_kwargs: ({'temperature': None, 'top_k': None, 'top_p': None, 'max_tokens': None}), limit: None, num_fewshot: None, batch_size: None > 2024-06-24 12:41:10,700 INFO: > | Tasks |Version|Filter|n-shot| Metric |Value | |Stderr| > |-------------|-------|------|-----:|--------|-----:|---|-----:| > |arc_challenge|Yaml |none | 0|acc |0.5334|± |0.0145| > | | |none | 0|acc_norm|0.5300|± |0.0146| > |hellaswag |Yaml |none | 0|acc |0.5716|± |0.0049| > | | |none | 0|acc_norm|0.7917|± |0.0043| > |openbookqa |Yaml |none | 0|acc |0.3210|± |0.0207| > | | |none | 0|acc_norm|0.4520|± |0.0223| > |piqa |Yaml |none | 0|acc |0.7997|± |0.0097| > | | |none | 0|acc_norm|0.8090|± |0.0095| > |winogrande |Yaml |none | 0|acc |0.7284|± |0.0130| > > ``` > [accordion] Generative Task > > The EEH flow also supports running generative (autoregressive) eval harness tasks, i.e. tasks that specify `output_type: generate_until` in the task specification, such as `triviaqa` or `drop`. Refer to task [triviqa](https://github.com/EleutherAI/lm-evaluation-harness/blob/4600d6bf73ba2cf7037ae7feada03315839ef185/lm_eval/tasks/triviaqa/default.yaml#L4) for an example specification from the official EEH repository. > > In order to run generative inference on CSX, you must specify the following inference settings in the model config of YAML file: > > * `start_token` - ID of the special token that indicates where to start inferring for each sample, as described above. You may specify a list of token IDs instead of a single ID. If you do, the model will start inference at the first token that matches any one of the provided IDs. The model will pad inferred predictions with the first ID in the list. > > * `stop_sequences` - List of sequences (each one being a list of token IDs). If any one of these sequences is emitted by the model, inference will stop for that sample. For example, suppose you would like to stop inferring after either a newline character (e.g. token id 1), or a combination of a period (e.g. token id 2) followed by a space (e.g. token id 3). In this case, set stop\_sequences to \[\[1], \[2, 3]]. To stop inferring after seeing a newline character only, set stop\_sequences to \[\[1]]. To disable this feature, set `stop_sequences` to an empty list \[]. Additionally, the following optional parameters may be set: > > * `max_tokens` - Maximum tokens to infer for each sample. > > * `loop_dim` - Indicates the sequence dimension in the input and output data. Default value is 1. If set to 0, indicates that both input and output data is transposed (i.e. `sequence X samples` instead of `samples X sequence`). > > For your LLaMA3 8B example, please update the YAML file `./llama3_8B_eeh.yaml` to add these inference settings: > > ```yaml theme={null} > trainer: > init: > backend: # CSX > ... > model: # Llama3-8B > name: llama > ... > # Inference Settings > start_token: 128256 # Set to `vocab_size` > stop_sequences: [[198], [13], [11]] # Respective tokens for "\n", "." and "," > max_tokens: 256 # Default from HF implementations > loop_dim: 1 > callbacks: > - EleutherEvalHarness: > # Eleuther Eval Harness settings > eeh_args: > tasks: triviaqa > num_fewshot: 0 > ... > ... > ``` > > > [!NOTE] > > > > 1. For `start_token`, it is ideal to choose a value that’s not going to be generated by the model, i.e. `vocab_size` in the example above. > > > > 2. The generative task itself defines `stop_sequences` under setting `generation_kwargs.until` of the task spec. For instance, [triviqa](https://github.com/EleutherAI/lm-evaluation-harness/blob/4600d6bf73ba2cf7037ae7feada03315839ef185/lm_eval/tasks/triviaqa/default.yaml#L12-L15) specifies `"\n"`, `"."` and `","` as the stop tokens. The EEH flow will internally override the `stop_sequences` config with the value from the task, so you can also specify an arbitrary value in the YAML. > > Finally, please update the bash script as follows: > > ```bash theme={null} > cszoo lm_eval ./llama3_8B_eeh.yaml \ > --target_device CSX \ > --checkpoint_path \ > --python_paths \ > --mount_dirs \ > ``` > > The output logs are as follows: > > ```bash theme={null} > ... > 2024-06-26 11:22:47,530 INFO: | EleutherAI Generative Eval Device=CSX, GlobalStep=1, Batch=4480, Rate=0.38 samples/sec, GlobalRate=0.38 samples/sec > 2024-06-26 11:22:47,553 INFO: | EleutherAI Generative Eval Device=CSX, GlobalStep=1, Batch=4485, Rate=0.38 samples/sec, GlobalRate=0.38 samples/sec > 2024-06-26 11:38:15,868 INFO: (None), gen_kwargs: ({'temperature': None, 'top_k': None, 'top_p': None, 'max_tokens': None}), limit: None, num_fewshot: None, batch_size: None > 2024-06-26 11:38:16,232 INFO: > | Tasks |Version| Filter |n-shot| Metric |Value | |Stderr| > |--------|------:|-----------------|-----:|-----------|-----:|---|-----:| > |triviaqa| 3|remove_whitespace| 0|exact_match|0.1120|± |0.0001| > ``` > > By default, the model will perform greedy sampling of the inferred tokens, i.e. for all of the model’s outputs, pick the token with the highest probability. > > In order to perform non-greedy sampling, you can pass in `temperature`, `top_k` or `top_p` to either the bash script or under `eeh_args` of the YAML. For example: > > ```bash theme={null} > cszoo lm_eval ./llama3_8B_eeh.yaml \ > --target_device CSX \ > --checkpoint_path \ > --python_paths \ > --mount_dirs \ > --temperature 0.7 \ > --top_k 10 \ > --top_p 0.95 \ > ``` > [accordion] Non-generative and Generative Tasks > > You can combine evaluation for generative and non-generative eval harness tasks simply via updating the bash script as follows: > > ```bash theme={null} > cszoo lm_eval ./llama3_8B_eeh.yaml \ > --target_device CSX \ > --tasks winogrande,drop \ > --checkpoint_path \ > --python_paths \ > --mount_dirs \ > ``` > > The output logs are as follows: > > ```bash theme={null} > ... > 2024-06-26 13:57:52,177 INFO: | EleutherAI Eval Device=CSX, GlobalStep=1, Batch=632, Rate=34.38 samples/sec, GlobalRate=34.34 samples/sec > 2024-06-26 13:57:52,206 INFO: | EleutherAI Eval Device=CSX, GlobalStep=1, Batch=633, Rate=34.39 samples/sec, GlobalRate=34.35 samples/sec > 2024-06-26 13:57:52,333 INFO: Running generate_until requests > ... > 2024-06-26 14:00:03,499 INFO: | EleutherAI Generative Eval Device=CSX, GlobalStep=1, Batch=2382, Rate=0.38 samples/sec, GlobalRate=0.38 samples/sec > 2024-06-26 14:00:03,519 INFO: | EleutherAI Generative Eval Device=CSX, GlobalStep=1, Batch=2383, Rate=0.38 samples/sec, GlobalRate=0.38 samples/sec > 2024-06-26 14:00:31,890 INFO: (None), gen_kwargs: ({'temperature': None, 'top_k': None, 'top_p': None, 'max_tokens': None}), limit: None, num_fewshot: None, batch_size: None > 2024-06-26 14:00:32,351 INFO: > | Tasks |Version|Filter|n-shot|Metric|Value | |Stderr| > |----------|------:|------|-----:|------|-----:|---|-----:| > |winogrande| 1|none | 0|acc |0.7284|± |0.0141| > |drop | 3|none | 0|em |0.0072|± |0.0008| > | | |none | 0|f1 |0.0371|± |0.0013| > > ``` > > > [!NOTE] > > > > 1. Since inference settings are baked into the model configuration and that inference requires different resources, there is a separate compile and execution for running downstream validation on generative tasks. > > > > 2. You may specify at most one generative task at a time (per callback). > [accordion] Run Multiple Generative Tasks > > In order to run multiple generative tasks, you may update the run script to the following: > > ```bash theme={null} > cszoo lm_eval ./llama3_8B_eeh.yaml \ > --target_device CSX \ > --tasks drop,gsm8k \ > --checkpoint_path \ > --python_paths \ > --mount_dirs \ > ``` ## What’s next? To run downstream validation on code generation tasks, please see check out: * [Downstream Validation using BigCode Eval Harness](../../model-zoo/core-workflows/downstream-validation-using-bigcode-eval-harness) You can also perform downstream validation using EEH as part of your pretraining runs with upstream validation. Check out the following guide: * [Pretraining with Downstream Validation](../../model-zoo/core-workflows/pretraining-with-upstream-validation) # Fine Tuning With Validation Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/core-workflows/fine-tuning-with-validation Learn how to configure and execute a fine-tuning run with upstream validation. We'll use the LLaMA3 8B model here as an example. By the end, you should be comfortable kicking off your own fine-tuning run for the model of your choice. Prerequisites * You must have installed the [Model Zoo](../../getting-started/setup-and-installation). * You must be familiar with the [Trainer](../../model-zoo/trainer-overview) and [YAML format](../../model-zoo/trainer-configuration-overview). * Please ensure you have read [Checkpointing](../../model-zoo/components/trainer-components/checkpointing). * Please ensure you have read [LLaMA3 8B pre-training](../../model-zoo/trainer-overview). ## Configuring the Run There are two main flows you can use to fine-tune a model: * Use a YAML configuration file and the Model Zoo CLI. * Use pure Python. They will be presented side-by-side so that you can compare the two flows as you progress through this tutorial. Start with the Trainer configured in [LLaMA3 8B pre-training](../../model-zoo/trainer-overview). You will only need to make a few changes to this configuration to accomodate a fine-tuning run. ### Fine-Tuning Using a Pre-trained Checkpoint To perform fine-tuning, a checkpoint from a previous training run is required. These checkpoints can be generated from previous runs or downloaded from online databases. For more information on porting a checkpoint from HuggingFace see [Port a Hugging Face model to Cerebras Model Zoo](../../model-zoo/migration/port-a-hugging-face-model-to-cerebras-model-zoo.mdx). In this tutorial you will assume a checkpoint has already been generated after finishing [Pretraining with Upstream Validation](../../model-zoo/core-workflows/pretraining-with-upstream-validation). For simplicty, let’s assume the checkpoint saved after the final step has the path: `./ckpts/checkpoint_10000.mdl` ### Configure Checkpoint State Loading To enable fine-tuning, only load the model state from the checkpoint. Other checkpoint states such as the optimizer state or the training step should be reset. If using a YAML, configure which states to load from the checkpoint using the [callbacks](../yaml/index.html#wsc-modelzoo-yaml-init-callbacks) key. For Python, configure which states to load from the checkpoint by constructing a [`LoadCheckpointStates`](.html#cerebras.modelzoo.trainer.callbacks.LoadCheckpointStates "cerebras.modelzoo.trainer.callbacks.LoadCheckpointStates") object as follows. ```yaml YAML theme={null} trainer: init: backend: # CSX ... model: # llama ... optimizer: # AdamW ... schedulers: # CosineDecayLR ... precision: # DLS ... loop: ... checkpoint: ... callbacks: ... - LoadCheckpointStates: load_checkpoint_states: "model" ... ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ( CheckLoss, Checkpoint, ComputeNorm, LoadCheckpointStates, MixedPrecision, ModelEvalMetrics, TrainingLoop, ) from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model as LLaMA3 trainer = Trainer( backend=cstorch.backend("CSX", ...), model=lambda: LLaMA3(...), optimizer=lambda model: cstorch.optim.AdamW(...), schedulers=[...], precision=MixedPrecision(...), loop=TrainingLoop(...), checkpoint=Checkpoint(...), callbacks=[ ..., LoadCheckpointStates("model"), ], ) ... ``` ### Load From a Checkpoint Configure the trainer to load a checkpoint from a given path. If using a YAML, add the `ckpt_path` parameter to the `fit` key. If using Python, specify `ckpt_path` in the Trainer’s [`fit`](../model-zoo/api/trainer-api#cerebras.modelzoo.Trainer.fit "cerebras.modelzoo.Trainer.fit") method as follows. ```yaml YAML theme={null} trainer: init: ... fit: train_dataloader: ... val_dataloader: - ... ckpt_path: ./ckpts/checkpoint_10000.mdl ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer(...) trainer.fit( train_dataloader=cstorch.utils.data.DataLoader( ..., ), val_dataloader=[ ..., ], ckpt_path="./ckpts/checkpoint_10000.mdl", ) ``` ### Putting It All Together After the above adjustments, you should have a configuration that looks like this: ```yaml YAML theme={null} trainer: init: backend: backend_type: CSX cluster_config: num_csx: 16 seed: 2024 model: # Embedding vocab_size: 128256 hidden_size: 4096 position_embedding_type: "rotary" pos_scaling_factor: 1.0 rope_theta: 500000.0 rotary_dim: 128 share_embedding_weights: false max_position_embeddings: 8192 embedding_dropout_rate: 0.0 embedding_layer_norm: false # Decoder num_hidden_layers: 32 dropout_rate: 0.0 layer_norm_epsilon: 1.0e-5 norm_type: "rmsnorm" # Decoder - Attention num_heads: 32 attention_type: "scaled_dot_product" attention_module: "multiquery_attention" attention_dropout_rate: 0.0 use_projection_bias_in_attention: false use_ffn_bias_in_attention: false extra_attention_params: num_kv_groups: 8 # Decoder - ffn filter_size: 14336 nonlinearity: "swiglu" use_ffn_bias: false # Task-specific use_bias_in_output: false loss_scaling: "num_tokens" loss_weight: 1.0 # Initializer initializer_range: 0.02 # Cerebras parameters mixed_precision: True fp16_type: "cbfloat16" optimizer: AdamW: betas: [0.9, 0.95] correct_bias: True weight_decay: 0.1 schedulers: - CosineDecayLR: initial_learning_rate: 3.0e-5 end_learning_rate: 3.0e-6 total_iters: 528 precision: fp16_type: cbfloat16 loss_scaling_factor: dynamic max_gradient_norm: 1.0 loop: num_steps: 10000 eval_frequency: 1000 eval_steps: 1000 checkpoint: steps: 1000 callbacks: - ComputeNorm: {} - CheckLoss: {} - LoadCheckpointStates: load_checkpoint_states: "model" - ModelEvalMetrics: {} loggers: - ProgressLogger: {} - TensorBoardLogger: {} fit: train_dataloader: data_processor: GptHDF5MapDataProcessor data_dir: "/data/llama_v3_dataset_vocab128256/train" batch_size: 80 micro_batch_size: 20 shuffle: False shuffle_seed: 1337 num_workers: 8 prefetch_factor: 10 persistent_workers: True # Important to avoid seeding at each epoch val_dataloader: - data_processor: GptHDF5MapDataProcessor data_dir: "/data/llama_v3_dataset_vocab128256/val" batch_size: 80 micro_batch_size: 20 shuffle: False shuffle_seed: 1337 num_workers: 8 prefetch_factor: 10 persistent_workers: True # Important to avoid seeding at each epoch ckpt_path: ./ckpts/checkpoint_10000.mdl ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ( CheckLoss, Checkpoint, ComputeNorm, MixedPrecision, ModelEvalMetrics, TrainingLoop, ) from cerebras.modelzoo.trainer.loggers import ( ProgessLogger, TensorBoardLogger, ) from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model as LLaMA3 trainer = Trainer( backend=cstorch.backend( backend_type="CSX", cluster_config=cstorch.distributed.ClusterConfig( num_csx=16, ), ), seed=2024, model=lambda: LLaMA3( # Embedding vocab_size=128256, hidden_size=4096, position_embedding_type="rotary", pos_scaling_factor=1.0, rope_theta=500000.0, rotary_dim=128, share_embedding_weights=False, max_position_embeddings=8192, embedding_dropout_rate=0.0, embedding_layer_norm=False, # Decoder num_hidden_layers=32, dropout_rate=0.0, layer_norm_epsilon=1.0e-5, norm_type="rmsnorm", # Decoder - Attention num_heads=32, attention_type="scaled_dot_product", attention_module="multiquery_attention", attention_dropout_rate=0.0, use_projection_bias_in_attention=False, use_ffn_bias_in_attention=False, extra_attention_params=dict( num_kv_groups=8, ), # Decoder - ffn filter_size=14336, nonlinearity="swiglu", use_ffn_bias=False, # Task-specific use_bias_in_output=False, loss_scaling="num_tokens", loss_weight=1.0, # Initializer initializer_range=0.02, # Cerebras parameters mixed_precision=True, fp16_type="cbfloat16", ), optimizer=lambda model: cstorch.optim.AdamW( model.parameters(), lr=0.01, # This is a placeholder betas=[0.9, 0.95], correct_bias=True, weight_decay: 0.1, ), schedulers=[ lambda optimizer: cstorch.optim.lr_scheduler.CosineDecayLR( initial_learning_rate=3.0e-5, end_learning_rate=3.0e-6, total_iters=528, ) ], precision=MixedPrecision( fp16_type="cbfloat16", loss_scaling_factor="dynamic", max_gradient_norm=1.0, ), loop=TrainingLoop( num_steps=10000, eval_frequency=1000, eval_steps=1000, ), checkpoint=Checkpoint(steps=1000), callbacks=[ ComputeNorm(), CheckLoss(), LoadCheckpointStates("model"), ModelEvalMetrics(), ], loggers=[ ProgessLogger(), TensorBoardLogger(), ], ) trainer.fit( train_dataloader=cstorch.utils.data.DataLoader( registry.get_data_processor("GptHDF5MapDataProcessor"), data_dir="/data/llama_v3_dataset_vocab128256/train", batch_size=80, micro_batch_size=20, shuffle=False, shuffle_seed=1337, num_workers=8, prefetch_factor=10, persistent_workers=True, # Important to avoid seeding at each epoch ), val_dataloader=[ cstorch.utils.data.DataLoader( registry.get_data_processor("GptHDF5MapDataProcessor"), data_dir="/data/llama_v3_dataset_vocab128256/val", batch_size=80, micro_batch_size=20, shuffle=False, shuffle_seed=1337, num_workers=8, prefetch_factor=10, persistent_workers=True, # Important to avoid seeding at each epoch ), ], ckpt_path="./ckpts/checkpoint_10000.mdl", ) ``` ## Start Fine-Tuning Now that you have a fully configured Trainer, kick off the run and start fine-tuning: ```bash YAML theme={null} cszoo fit ./finetune_llama_8b.yaml ``` ```python Python theme={null} python ./finetune_llama_8b.py ``` ### Monitor the Run Once compilation finishes and the Wafer-Scale Cluster is programmed for execution, you should start seeing progress logs that look like ``` | Train Device=CSX, Step=1, Loss=1.41992, Rate=16.30 samples/sec, GlobalRate=16.30 samples/sec | Train Device=CSX, Step=2, Loss=1.41016, Rate=20.40 samples/sec, GlobalRate=19.13 samples/sec | Train Device=CSX, Step=3, Loss=1.39062, Rate=21.93 samples/sec, GlobalRate=20.25 samples/sec | Train Device=CSX, Step=4, Loss=1.38281, Rate=22.45 samples/sec, GlobalRate=20.84 samples/sec | Train Device=CSX, Step=5, Loss=1.36719, Rate=22.57 samples/sec, GlobalRate=21.17 samples/sec | Train Device=CSX, Step=6, Loss=1.42188, Rate=22.54 samples/sec, GlobalRate=21.39 samples/sec | Train Device=CSX, Step=7, Loss=1.39258, Rate=22.52 samples/sec, GlobalRate=21.54 samples/sec | Train Device=CSX, Step=8, Loss=1.36914, Rate=22.44 samples/sec, GlobalRate=21.64 samples/sec | Train Device=CSX, Step=9, Loss=1.37695, Rate=22.33 samples/sec, GlobalRate=21.71 samples/sec | Train Device=CSX, Step=10, Loss=1.35938, Rate=22.38 samples/sec, GlobalRate=21.78 samples/sec | Train Device=CSX, Step=11, Loss=1.36719, Rate=21.32 samples/sec, GlobalRate=21.67 samples/sec | Train Device=CSX, Step=12, Loss=1.39844, Rate=21.72 samples/sec, GlobalRate=21.69 samples/sec | Train Device=CSX, Step=13, Loss=1.38672, Rate=21.88 samples/sec, GlobalRate=21.71 samples/sec | Train Device=CSX, Step=14, Loss=1.34961, Rate=21.91 samples/sec, GlobalRate=21.73 samples/sec | Train Device=CSX, Step=15, Loss=1.33203, Rate=21.88 samples/sec, GlobalRate=21.74 samples/sec | Train Device=CSX, Step=16, Loss=1.33008, Rate=21.91 samples/sec, GlobalRate=21.75 samples/sec | Train Device=CSX, Step=17, Loss=1.33984, Rate=21.88 samples/sec, GlobalRate=21.76 samples/sec | Train Device=CSX, Step=18, Loss=1.31250, Rate=21.88 samples/sec, GlobalRate=21.76 samples/sec | Train Device=CSX, Step=19, Loss=1.36133, Rate=21.91 samples/sec, GlobalRate=21.77 samples/sec | Train Device=CSX, Step=20, Loss=1.30664, Rate=23.15 samples/sec, GlobalRate=21.87 samples/sec | Train Device=CSX, Step=21, Loss=1.30078, Rate=22.52 samples/sec, GlobalRate=21.88 samples/sec | Train Device=CSX, Step=22, Loss=1.31250, Rate=22.23 samples/sec, GlobalRate=21.89 samples/sec | Train Device=CSX, Step=23, Loss=1.30664, Rate=21.10 samples/sec, GlobalRate=21.82 samples/sec | Train Device=CSX, Step=24, Loss=1.30469, Rate=22.73 samples/sec, GlobalRate=21.90 samples/sec | Train Device=CSX, Step=25, Loss=1.28906, Rate=21.42 samples/sec, GlobalRate=21.84 samples/sec ... | Eval Device=CSX, GlobalStep=1000, Batch=1, Loss=1.21875, Rate=21.47 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=2, Loss=1.24219, Rate=22.65 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=3, Loss=1.26562, Rate=22.06 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=4, Loss=1.25195, Rate=21.90 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=5, Loss=1.27539, Rate=21.80 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=6, Loss=1.23047, Rate=21.79 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=7, Loss=1.22852, Rate=20.72 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=8, Loss=1.27734, Rate=21.24 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=9, Loss=1.23633, Rate=22.57 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=10, Loss=1.27930, Rate=22.10 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=11, Loss=1.23438, Rate=20.86 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=12, Loss=1.24609, Rate=21.31 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=13, Loss=1.23633, Rate=21.47 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=14, Loss=1.23633, Rate=21.48 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=15, Loss=1.21680, Rate=22.66 samples/sec, GlobalRates=21.66 samples/sec ... ``` > [!NOTE] > > The performance numbers that you get will vary depending on how many Cerebras systems you are using and which generation systems you are using. If you open up the TensorBoard you can more closely monitor the run be observing the trends in the graphs of the various logged metrics. ``` tensorboard --bind_all --logdir="./model_dir" ``` ![tensorboard](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/LLaMA3_8B_Finetuning.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=593bbfb04b862f79287b8c9b64e6bfc9) As can be seen above, the screenshots were taken at around step 8000. At this point you can observe that so far, the run seems to progressing well. The losses appear to be trending downwards and the model wise gradient norms don’t appear overly abnormal. ## Porting the Model to Hugging Face Once the fine-tuning run has finished, you can port the model and checkpoint to Hugging Face. To learn more about how to do this, see [Port a trained and fine-tuned model to Hugging Face](../../model-zoo/migration/port-a-hugging-face-model-to-cerebras-model-zoo). ## Conclusion With that, you have completed your first fine-tuning run with validation on the Cerebras Wafer-Scale Cluster using the ModelZoo Trainer! By now, you should understand how to write your own Trainer configuration and how to kick off a training job from a checkpoint on the Cerebras Wafer-Scale Cluster. You can now take this knowledge and fine-tune your very own model. # Pretraining With Downstream Validation Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/core-workflows/pretraining-with-downstream-validation Learn how to configure downstream validation as part of your pretraining workflow. On this page, you’ll build on the [Pretraining with Upstream Validation](../../model-zoo/core-workflows/pretraining-with-upstream-validation) guide. The example will be for pretraining Llama-3-8B model. For downstream validation, you'll use the external frameworks Eleuther Eval Harness (EEH) and BigCode Eval Harness (BCEH). By the end of this guide, you should be comfortable kicking off your own pretraining run for the model of your [choice](../../model-zoo/core-workflows/pretraining-with-upstream-validation), combining both upstream and downstream validation. ## Prerequisites Before beginning this guide, make sure you've: * Completed [setup and installation](../getting-started/setup-and-installation). * Read [Trainer Essentials](../../model-zoo/trainer-overview) and [Trainer Configuration](../../model-zoo/trainer-configuration-overview) which cover the basics of running models in Model Zoo. * Read [Pretraining with Upstream Validation](../../model-zoo/core-workflows/pretraining-with-upstream-validation) as this guide directly builds on the walkthrough there. * Read [Downstream Validation Using Eleuther Eval Harness](../../model-zoo/core-workflows/downstream-validation-using-eleuther-eval-harness) and [Downstream Validation using BigCode Eval Harness](../../model-zoo/core-workflows/downstream-validation-using-bigcode-eval-harness)). ## Configure the Run Similar to [Pretraining with Upstream Validation](../../model-zoo/core-workflows/pretraining-with-upstream-validation), this page will present the YAML configuration file as well as the equivalent pure Python setup side-by-side for your ease of comparison. You will add downstream validation to the pretraining configuration set up in [Pretraining with Upstream Validation](../../model-zoo/core-workflows/pretraining-with-upstream-validation) for Llama-3-8B. Recall the full configuration you put together from that tutorial: ```yaml YAML theme={null} trainer: init: backend: backend_type: CSX cluster_config: num_csx: 16 seed: 2024 model: # Embedding vocab_size: 128256 hidden_size: 4096 position_embedding_type: "rotary" pos_scaling_factor: 1.0 rope_theta: 500000.0 rotary_dim: 128 share_embedding_weights: false max_position_embeddings: 8192 embedding_dropout_rate: 0.0 embedding_layer_norm: false # Decoder num_hidden_layers: 32 dropout_rate: 0.0 layer_norm_epsilon: 1.0e-5 norm_type: "rmsnorm" # Decoder - Attention num_heads: 32 attention_type: "scaled_dot_product" attention_module: "multiquery_attention" attention_dropout_rate: 0.0 use_projection_bias_in_attention: false use_ffn_bias_in_attention: false extra_attention_params: num_kv_groups: 8 # Decoder - ffn filter_size: 14336 nonlinearity: "swiglu" use_ffn_bias: false # Task-specific use_bias_in_output: false loss_scaling: "num_tokens" loss_weight: 1.0 # Initializer initializer_range: 0.02 # Cerebras parameters mixed_precision: True fp16_type: "cbfloat16" optimizer: AdamW: betas: [0.9, 0.95] correct_bias: True weight_decay: 0.1 schedulers: - CosineDecayLR: initial_learning_rate: 3.0e-5 end_learning_rate: 3.0e-6 total_iters: 528 precision: fp16_type: cbfloat16 loss_scaling_factor: dynamic max_gradient_norm: 1.0 loop: num_steps: 10000 eval_frequency: 1000 eval_steps: 1000 checkpoint: steps: 1000 callbacks: - ComputeNorm: {} - CheckLoss: {} - ModelEvalMetrics: {} loggers: - ProgressLogger: {} - TensorBoardLogger: {} fit: train_dataloader: data_processor: GptHDF5MapDataProcessor data_dir: "/data/llama_v3_dataset_vocab128256/train" batch_size: 80 micro_batch_size: 20 shuffle: False shuffle_seed: 1337 num_workers: 8 prefetch_factor: 10 persistent_workers: True # Important to avoid seeding at each epoch val_dataloader: - data_processor: GptHDF5MapDataProcessor data_dir: "/data/llama_v3_dataset_vocab128256/val" batch_size: 80 micro_batch_size: 20 shuffle: False shuffle_seed: 1337 num_workers: 8 prefetch_factor: 10 persistent_workers: True # Important to avoid seeding at each epoch ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ( CheckLoss, Checkpoint, ComputeNorm, MixedPrecision, ModelEvalMetrics, TrainingLoop, ) from cerebras.modelzoo.trainer.loggers import ( ProgessLogger, TensorBoardLogger, ) from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model as LLaMA3 trainer = Trainer( backend=cstorch.backend( backend_type="CSX", cluster_config=cstorch.distributed.ClusterConfig( num_csx=16, ), ), seed=2024, model=lambda: LLaMA3( # Embedding vocab_size=128256, hidden_size=4096, position_embedding_type="rotary", pos_scaling_factor=1.0, rope_theta=500000.0, rotary_dim=128, share_embedding_weights=False, max_position_embeddings=8192, embedding_dropout_rate=0.0, embedding_layer_norm=False, # Decoder num_hidden_layers=32, dropout_rate=0.0, layer_norm_epsilon=1.0e-5, norm_type="rmsnorm", # Decoder - Attention num_heads=32, attention_type="scaled_dot_product", attention_module="multiquery_attention", attention_dropout_rate=0.0, use_projection_bias_in_attention=False, use_ffn_bias_in_attention=False, extra_attention_params=dict( num_kv_groups=8, ), # Decoder - ffn filter_size=14336, nonlinearity="swiglu", use_ffn_bias=False, # Task-specific use_bias_in_output=False, loss_scaling="num_tokens", loss_weight=1.0, # Initializer initializer_range=0.02, # Cerebras parameters mixed_precision=True, fp16_type="cbfloat16", ), optimizer=lambda model: cstorch.optim.AdamW( model.parameters(), lr=0.01, # This is a placeholder betas=[0.9, 0.95], correct_bias=True, weight_decay: 0.1, ), schedulers=[ lambda optimizer: cstorch.optim.lr_scheduler.CosineDecayLR( initial_learning_rate=3.0e-5, end_learning_rate=3.0e-6, total_iters=528, ) ], precision=MixedPrecision( fp16_type="cbfloat16", loss_scaling_factor="dynamic", max_gradient_norm=1.0, ), loop=TrainingLoop( num_steps=10000, eval_frequency=1000, eval_steps=1000, ), checkpoint=Checkpoint(steps=1000), callbacks=[ ComputeNorm(), CheckLoss(), ModelEvalMetrics(), ], loggers=[ ProgessLogger(), TensorBoardLogger(), ], ) trainer.fit( train_dataloader=cstorch.utils.data.DataLoader( registry.get_data_processor("GptHDF5MapDataProcessor"), data_dir="/data/llama_v3_dataset_vocab128256/train", batch_size=80, micro_batch_size=20, shuffle=False, shuffle_seed=1337, num_workers=8, prefetch_factor=10, persistent_workers=True, # Important to avoid seeding at each epoch ), val_dataloader=[ cstorch.utils.data.DataLoader( registry.get_data_processor("GptHDF5MapDataProcessor"), data_dir="/data/llama_v3_dataset_vocab128256/val", batch_size=80, micro_batch_size=20, shuffle=False, shuffle_seed=1337, num_workers=8, prefetch_factor=10, persistent_workers=True, # Important to avoid seeding at each epoch ), ] ) ``` ### Configure EEH Let’s add downstream validation on a single EEH multiple-choice task `winogrande` as part of the pretraining run. To do this, you will need to augment the configuration with the [`EleutherEvalHarness`](../../model-zoo/core-workflows/downstream-validation-using-eleuther-eval-harness) callback as such: ```yaml YAML theme={null} trainer: init: backend: # CSX ... model: # llama ... optimizer: # AdamW ... schedulers: # CosineDecayLR ... precision: # DLS ... loop: ... checkpoint: ... callbacks: ... - EleutherEvalHarness: # Eleuther Eval Harness settings eeh_args: tasks: winogrande num_fewshot: 0 # CSX-specific eval harness settings keep_data_dir: false # Dataloader settings batch_size: 4 shuffle: false max_sequence_length: 8192 num_workers: 1 data_dir: tokenizer_file_path: eos_id: 128001 pretrained_model_name_or_path: null loggers: ... seed: 2024 ... ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ( Checkpoint, MixedPrecision, TrainingLoop, ) from cerebras.modelzoo.trainer.extensions.eleuther import ( EleutherEvalHarness, ) from cerebras.modelzoo.trainer.extensions.eleuther.eval_harness_utils import ( EleutherCLIArgs, ) from cerebras.modelzoo.trainer.loggers import ( ProgessLogger, TensorBoardLogger, ) from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model as LLaMA3 eval_harness = EleutherEvalHarness( # Eleuther Eval Harness settings eeh_args=EleutherCLIArgs( tasks="winogrande", num_fewshot=0, ), # CSX-specific eval harness settings keep_data_dir=False, # DataLoader Settings data_dir=, batch_size=4, max_sequence_length=8192, tokenizer_file_path=, eos_id=128001, ) trainer = Trainer( backend=cstorch.backend("CSX", ...), model=lambda: LLaMA3(...), optimizer=lambda model: cstorch.optim.AdamW(...), schedulers=[...], precision=MixedPrecision(...), loop=TrainingLoop(...), checkpoint=Checkpoint(...), callbacks=[ eval_harness, ... ], loggers=[...], seed=2024, ) trainer.fit( train_dataloader=cstorch.utils.data.DataLoader(...), val_dataloader=[ cstorch.utils.data.DataLoader(...), ] ) ``` As part of your pretraining run’s configuration, you have now set up downstream validation on EEH task `winogrande`. > [!NOTE] > > 1. The `eval_frequency` specified as part of the trainer’s loop (YAML) or in the `TrainingLoop` object (Python) also controls the frequency of downstream validation; i.e., for your example above, validation on EEH task `winogrande` will be run every 1K steps. > > 2. Update the `tasks` argument to configure downstream validation for more EEH tasks. Note that only a single generative EEH task may be specified per callback. ### Configure BCEH Configuring downstream validation using BCEH is no different than it is for EEH. For example, if you want to configure the pretraining run on the code generative task `humaneval`, please augment the YAML configuration file with the the [`BigCodeEvalHarness`](cerebras.modelzoo.trainer.extensions.bigcode.BigCodeEvalHarness "cerebras.modelzoo.trainer.extensions.bigcode.BigCodeEvalHarness") callback as such: * YAML: Simply add the callback to the list of callbacks in the YAML. Don’t forget to include the inference settings under model configuration! * Python: Construct a [`BigCodeEvalHarness`](../../model-zoo/core-workflows/downstream-validation-using-bigcode-eval-harness) callback object and pass it to the Trainer’s constructor as follows. Note that the BCEH arguments are passed to the callback via the `BigCodeCLIArgs` object, comprising the list of supported BCEH command line arguments. ```yaml YAML theme={null} trainer: init: backend: # CSX ... model: # llama ... # Inference Settings start_token: 128256 # Set to `vocab_size` stop_sequences: [] # Left empty as stop_sequences are overridden from the BCEH task max_tokens: 256 # Default from HF implementations loop_dim: 1 optimizer: # AdamW ... schedulers: # CosineDecayLR ... precision: # DLS ... loop: ... checkpoint: ... callbacks: ... - BigCodeEvalHarness: # BigCode Eval Harness settings bigcode_args: tasks: humaneval # CSX-specific eval harness settings keep_data_dir: false # Dataloader settings batch_size: 4 shuffle: false max_sequence_length: 8192 num_workers: 1 data_dir: tokenizer_file_path: eos_id: 128001 pretrained_model_name_or_path: null loggers: ... seed: 2024 ... ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ( Checkpoint, MixedPrecision, TrainingLoop, ) from cerebras.modelzoo.trainer.extensions.bigcode import ( BigCodeCLIArgs, BigCodeEvalHarness, ) from cerebras.modelzoo.trainer.loggers import ( ProgessLogger, TensorBoardLogger, ) from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model as LLaMA3 bc_eval_harness = BigCodeEvalHarness( # BigCode Eval Harness settings bch_args=BigCodeCLIArgs(tasks="humaneval"), # CSX-specific eval harness settings keep_data_dir=False, # DataLoader Settings data_dir=, batch_size=4, max_sequence_length=8192, tokenizer_file_path=, eos_id=128001, ) trainer = Trainer( backend=cstorch.backend("CSX", ...), model=lambda: LLaMA3( ..., # Inference Settings start_token=128256, # Set to `vocab_size` stop_sequences=[], # Left empty as stop_sequences are overridden from the BCEH task max_tokens=256, # Default from HF implementations loop_dim=1, ), optimizer=lambda model: cstorch.optim.AdamW(...), schedulers=[...], precision=MixedPrecision(...), loop=TrainingLoop(...), checkpoint=Checkpoint(...), callbacks=[ bc_eval_harness, ... ], loggers=[...], seed=2024, ) trainer.fit( train_dataloader=cstorch.utils.data.DataLoader(...), val_dataloader=[ cstorch.utils.data.DataLoader(...), ] ) ``` And that is all! As part of your pretraining run’s configuration, you have now set up downstream validation on BCEH task `humaneval`. > [!NOTE] > > 1. Since only running one generative eval harness task is supported per callback, please create a separate [`BigCodeEvalHarness`](../../model-zoo/core-workflows/downstream-validation-using-bigcode-eval-harness) callback to run downstream validation for more BCEH tasks. > > 2. To obtain the final eval metrics for BCEH, please run the code execution and evaluation flow separately using the [Downstream Validation using BigCode Eval Harness](../../model-zoo/core-workflows/downstream-validation-using-bigcode-eval-harness) guide. ### Configure EEH and BCEH Configuring downstream validation for both EEH and BCEH is also straightforward via the use of both the [`BigCodeEvalHarness`](../../model-zoo/core-workflows/downstream-validation-using-bigcode-eval-harness) callbacks. Let’s augment the full YAML configuration file to run downstream validation on EEH tasks `hellaswag`, `gsm8k` and `winogrande`, and BCEH task `mbpp` with the callbacks as follows: * YAML: Simply add both callbacks to the list of callbacks in the YAML. Since you are running generative eval harness tasks, don’t forget to include the inference settings under model configuration! * Python: Construct [`BigCodeEvalHarness`](../../model-zoo/core-workflows/downstream-validation-using-bigcode-eval-harness) objects, respectively. ```yaml YAML theme={null} trainer: init: backend: # CSX ... model: # llama ... # Inference Settings start_token: 128256 # Set to `vocab_size` stop_sequences: [] # Left empty as stop_sequences are overridden from the BCEH task max_tokens: 256 # Default from HF implementations loop_dim: 1 optimizer: # AdamW ... schedulers: # CosineDecayLR ... precision: # DLS ... loop: ... checkpoint: ... callbacks: ... - BigCodeEvalHarness: # BigCode Eval Harness settings bs_args: tasks: mbpp # CSX-specific eval harness settings keep_data_dir: false # Dataloader settings batch_size: 4 shuffle: false max_sequence_length: 8192 num_workers: 1 data_dir: tokenizer_file_path: eos_id: 128001 pretrained_model_name_or_path: null - EleutherEvalHarness: # Eleuther Eval Harness settings eeh_args: tasks: hellaswag,gsm8k,winogrande num_fewshot: 0 # CSX-specific eval harness settings keep_data_dir: false # Dataloader settings batch_size: 4 shuffle: false max_sequence_length: 8192 num_workers: 1 data_dir: tokenizer_file_path: eos_id: 128001 pretrained_model_name_or_path: null loggers: ... seed: 2024 ... ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ( Checkpoint, MixedPrecision, TrainingLoop, ) from cerebras.modelzoo.trainer.extensions.bigcode import ( BigCodeCLIArgs, BigCodeEvalHarness, ) from cerebras.modelzoo.trainer.extensions.eleuther import ( EleutherEvalHarness, ) from cerebras.modelzoo.trainer.extensions.eleuther.eval_harness_utils import ( EleutherCLIArgs, ) from cerebras.modelzoo.trainer.loggers import ( ProgessLogger, TensorBoardLogger, ) from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model as LLaMA3 eval_harness = EleutherEvalHarness( # Eleuther Eval Harness settings eeh_args=EleutherCLIArgs( tasks="hellaswag,gsm8k,winogrande", num_fewshot=0, ), # CSX-specific eval harness settings keep_data_dir=False, # DataLoader Settings data_dir=, batch_size=4, max_sequence_length=8192, tokenizer_file_path=, eos_id=128001, ) bc_eval_harness = BigCodeEvalHarness( # BigCode Eval Harness settings bch_args=BigCodeCLIArgs(tasks="mbpp"), # CSX-specific eval harness settings keep_data_dir=False, # DataLoader Settings data_dir=, batch_size=4, max_sequence_length=8192, tokenizer_file_path=, eos_id=128001, ) trainer = Trainer( backend=cstorch.backend("CSX", ...), model=lambda: LLaMA3( ..., # Inference Settings start_token=128256, # Set to `vocab_size` stop_sequences=[], # Left empty as stop_sequences are overridden from the BCEH task max_tokens=256, # Default from HF implementations loop_dim=1, ), optimizer=lambda model: cstorch.optim.AdamW(...), schedulers=[...], precision=MixedPrecision(...), loop=TrainingLoop(...), checkpoint=Checkpoint(...), callbacks=[ eval_harness, bc_eval_harness, ... ], loggers=[...], seed=2024, ) trainer.fit( train_dataloader=cstorch.utils.data.DataLoader(...), val_dataloader=[ cstorch.utils.data.DataLoader(...), ] ) ``` And that is all! As part of your pretraining run’s configuration, you have now set up downstream validation on both BCEH and EEH tasks. ## Start Pretraining Once you have a fully configured Trainer, with your choice of downstream validation, all you need to do now is to kick off the run and start pretraining. * YAML: Let’s assume that the YAML configuration that you put together above is written to a file called `./pretrain_downstream_llama_8b.yaml`. To run pretraining use the CLI command. * Python: Let’s assume that the python code that you put together above is written to a file called `./pretrain_downstream_llama_8b.py`. To run pretraining, execute that python script. ```bash YAML theme={null} cszoo fit ./pretrain_downstream_llama_8b.yaml ``` ```python Python theme={null} python ./pretrain_downstream_llama_8b.py ``` # Pretraining With Upstream Validation Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/core-workflows/pretraining-with-upstream-validation Learn how to configure and execute a pretraining run with upstream validation. In this guide, you’ll be pretraining a LLaMA3 8B model. By the end, you should be comfortable kicking off your own pretraining run for the model of your choice. ## Prerequisites Before beginning this guide, make sure you've: * Completed [setup and installation](../getting-started/setup-and-installation) * Read through [Trainer Essentials](../../model-zoo/trainer-overview) and [Trainer Configuration](../../model-zoo/trainer-configuration-overview) which cover the basics of running models in Model Zoo. ## Configure the Run This page will cover the two main flows you can employ to perform pretraining. One using a YAML configuration file and a training script that is packaged in the Cerebras ModelZoo. The other using pure Python to run on your own. They will be presented side-by-side so that you can compare the two flows as you progress through this tutorial. If you aren’t interested in seeing the break down of the configuration, you can skip ahead to the [Putting It All Together](../../model-zoo/core-workflows/pretraining-with-upstream-validation#putting-it-all-together) section to see the full configuration. ### Configure the Wafer-Scale Cluster Let’s first figure out how much resources you’ll want to use for this pretraining job. In this example, let’s use a 16 node Wafer-Scale Cluster. To configure this, you can specify the number of Cerebras systems to use. ```yaml YAML theme={null} trainer: init: backend: backend_type: CSX cluster_config: num_csx: 16 ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( backend=cstorch.backend( backend_type="CSX", cluster_config=cstorch.distributed.ClusterConfig( num_csx=16, ), ), ..., ) ... ``` Notice how you can change cluster configuration parameters like `num_csx` to scale the run without making any changes to the model itself. ### Configure the Model Here you will be pretraining the LLaMA3 model class that comes packaged inside of the Cerebras ModelZoo. The LLaMA3 model by default will compute the accuracy and perplexity metrics during upstream validation. * YAML: To configure the LLaMA3 8B model, you specify the following parameters to the [model](../../model-zoo/trainer-configuration-overview) key. * Python: To configure the LLaMA3 8B model, you construct the model inside a lambda to take advantage of the Trainer’s efficient weight initialization feature. LLaMA3 is just a configuration of GPT2, hence why you are importing and initializing a `Gpt2Model` class. ```yaml YAML theme={null} trainer: init: backend: # CSX ... model: # Embedding vocab_size: 128256 hidden_size: 4096 position_embedding_type: "rotary" pos_scaling_factor: 1.0 rope_theta: 500000.0 rotary_dim: 128 share_embedding_weights: false max_position_embeddings: 8192 embedding_dropout_rate: 0.0 embedding_layer_norm: false # Decoder num_hidden_layers: 32 dropout_rate: 0.0 layer_norm_epsilon: 1.0e-5 norm_type: "rmsnorm" # Decoder - Attention num_heads: 32 attention_type: "scaled_dot_product" attention_module: "multiquery_attention" attention_dropout_rate: 0.0 use_projection_bias_in_attention: false use_ffn_bias_in_attention: false extra_attention_params: num_kv_groups: 8 # Decoder - ffn filter_size: 14336 nonlinearity: "swiglu" use_ffn_bias: false # Task-specific use_bias_in_output: false loss_scaling: "num_tokens" loss_weight: 1.0 # Initializer initializer_range: 0.02 # Cerebras parameters mixed_precision: True fp16_type: "cbfloat16" ... ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model as LLaMA3 trainer = Trainer( backend=cstorch.backend("CSX", ...), model=lambda: LLaMA3( # Embedding vocab_size=128256, hidden_size=4096, position_embedding_type="rotary", pos_scaling_factor=1.0, rope_theta=500000.0, rotary_dim=128, share_embedding_weights=False, max_position_embeddings=8192, embedding_dropout_rate=0.0, embedding_layer_norm=False, # Decoder num_hidden_layers=32, dropout_rate=0.0, layer_norm_epsilon=1.0e-5, norm_type="rmsnorm", # Decoder - Attention num_heads=32, attention_type="scaled_dot_product", attention_module="multiquery_attention", attention_dropout_rate=0.0, use_projection_bias_in_attention=False, use_ffn_bias_in_attention=False, extra_attention_params=dict( num_kv_groups=8, ), # Decoder - ffn filter_size=14336, nonlinearity="swiglu", use_ffn_bias=False, # Task-specific use_bias_in_output=False, loss_scaling="num_tokens", loss_weight=1.0, # Initializer initializer_range=0.02, # Cerebras parameters mixed_precision=True, fp16_type="cbfloat16", ), ..., ) ... ``` ### Configure the Optimizer Here you will be using the [`AdamW`](https://training-api.cerebras.ai/en/latest/cs-torch/cerebras-pytorch-api/cerebras-pytorch-optim) optimizer to optimize our model during pretraining. * YAML: To configure the [`AdamW`](https://training-api.cerebras.ai/en/latest/cs-torch/cerebras-pytorch-api/cerebras-pytorch-optim) key. Note, you don’t specify a learning rate here as you will configure a learning rate scheduler, just below. * Python: Note, you specified a placeholder learning rate of `0.01` here as you will configure a learning rate scheduler, just below. ```yaml YAML theme={null} trainer: init: backend: # CSX ... model: # llama ... optimizer: AdamW: betas: [0.9, 0.95] correct_bias: True weight_decay: 0.1 ``` ```python Python theme={null} To configure the [`AdamW`](../cs-torch/cerebras-pytorch-api/cerebras-pytorch-optim) optimizer, you can construct it as follows. import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model as LLaMA3 trainer = Trainer( backend=cstorch.backend("CSX", ...), model=lambda: LLaMA3(...), optimizer=lambda model: cstorch.optim.AdamW( model.parameters(), lr=0.01, # This is a placeholder betas=[0.9, 0.95], correct_bias=True, weight_decay: 0.1, ), ..., ) ... ``` ### Configure a Learning Rate Scheduler Here you will be using a [`CosineDecayLR`](https://training-api.cerebras.ai/en/latest/cs-torch/cerebras-pytorch-api/cerebras-pytorch-optim) learning rate scheduler. To configure the [`CosineDecayLR`](https://training-api.cerebras.ai/en/latest/cs-torch/cerebras-pytorch-api/cerebras-pytorch-optim) key. ```yaml YAML theme={null} trainer: init: backend: # CSX ... model: # llama ... optimizer: # AdamW ... schedulers: - CosineDecayLR: initial_learning_rate: 3.0e-5 end_learning_rate: 3.0e-6 total_iters: 528 ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model as LLaMA3 trainer = Trainer( backend=cstorch.backend("CSX", ...), model=lambda: LLaMA3(...), optimizer=lambda model: cstorch.optim.AdamW(...), schedulers=[ lambda optimizer: cstorch.optim.lr_scheduler.CosineDecayLR( initial_learning_rate=3.0e-5, end_learning_rate=3.0e-6, total_iters=528, ), ], ..., ) ... ``` ### Configure Mixed Precision and Gradient Scaling To get better performance, let’s use mixed precision in the run. More specifically, let’s configure the cluster to use `cbfloat16` as the lower precision type (see [CB16 Half-Precision](https://training-docs.cerebras.ai/en/latest/original/general/cs-1-data-formats.html#cb16-original) for more details on the `cbfloat16` data format). Since a lower precision is being used for activations, you’ll want to scale the gradients to prevent underflowing. Let’s use dynamic loss scaling for this run. In addition, to prevent gradients from exploding, let’s also clip the gradients based on its norm. * YAML: To configure the precision type and gradient scaling, you can specify the following parameters to the [precision](../../model-zoo/trainer-configuration-overview) key. * Python: To configure the precision type and gradient scaling, you can construct a [`MixedPrecision`](../../model-zoo/trainer-configuration-overview) object as follows. ```yaml YAML theme={null} trainer: init: backend: # CSX ... model: # llama ... optimizer: # AdamW ... schedulers: # CosineDecayLR ... precision: fp16_type: cbfloat16 loss_scaling_factor: dynamic max_gradient_norm: 1.0 ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import MixedPrecision from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model as LLaMA3 trainer = Trainer( backend=cstorch.backend("CSX", ...), model=lambda: LLaMA3(...), optimizer=lambda model: cstorch.optim.AdamW(...), schedulers=[...], precision=MixedPrecision( fp16_type="cbfloat16", loss_scaling_factor="dynamic", max_gradient_norm=1.0, ), ..., ) ... ``` ### Configure the Training/Validation Loop For this tutorial, let’s pre-train the model for 10k steps and run validation every 1k steps. * YAML: To configure the number of training and validation steps you can specify the following parameters to the [loop](../../model-zoo/trainer-configuration-overview) key. * Python: To configure the number of training and validation steps, you can construct a [`TrainingLoop`](../../model-zoo/trainer-configuration-overview) object as follows. ```yaml YAML theme={null} trainer: init: backend: # CSX ... model: # llama ... optimizer: # AdamW ... schedulers: # CosineDecayLR ... precision: # DLS ... loop: num_steps: 10000 eval_frequency: 1000 eval_steps: 1000 ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import MixedPrecision, TrainingLoop from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model as LLaMA3 trainer = Trainer( backend=cstorch.backend("CSX", ...), model=lambda: LLaMA3(...), optimizer=lambda model: cstorch.optim.AdamW(...), schedulers=[...], precision=MixedPrecision(...), loop=TrainingLoop( num_steps=10000, eval_frequency=1000, eval_steps=1000, ), ..., ) ... ``` ### Configure Checkpointing In case you want to restart training from some point in the middle with different hyperparameters, let’s save a checkpoint every 1000 steps of training. This conveniently lines up nicely with the validation frequency you specified above so that you’ll know how well the model was performing at each checkpoint. * YAML: To configure how often checkpoints are taken, you specify the following parameters to the [checkpoint](../../model-zoo/trainer-configuration-overview) key. * Python: To configure how often checkpoints are taken, you can construct a [`Checkpoint`](../../model-zoo/trainer-configuration-overview) object as follows. ```yaml YAML theme={null} trainer: init: backend: \# CSX ... model: \# llama ... optimizer: \# AdamW ... schedulers: \# CosineDecayLR ... precision: \# DLS ... loop: ... checkpoint: steps: 1000 ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ( Checkpoint, MixedPrecision, TrainingLoop, ) from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model as LLaMA3 trainer = Trainer( backend=cstorch.backend("CSX", ...), model=lambda: LLaMA3(...), optimizer=lambda model: cstorch.optim.AdamW(...), schedulers=\[...\], precision=MixedPrecision(...), loop=TrainingLoop(...), checkpoint=Checkpoint(steps=1000), ..., ) ... ``` ### Configure Callbacks The following steps are completely optional. For this pretraining run, let’s keep track of the gradient norms to make sure that the model numerics are stable. In addition, let’s ensure that the loss values that the model is outputting are valid (i.e. not `NaN` or `inf`). Finally, since upstream validation is being run, let’s make sure that the validation metrics that are computed are being logged. * YAML: To configure these checks, you can specify the following callbacks to the [callbacks](../../model-zoo/trainer-configuration-overview) key. * Python: To configure these checks, you can construct the following callbacks and pass them to the trainer. ```yaml YAML theme={null} trainer: init: backend: # CSX ... model: # llama ... optimizer: # AdamW ... schedulers: # CosineDecayLR ... precision: # DLS ... loop: ... checkpoint: ... callbacks: - ComputeNorm: {} - CheckLoss: {} - ModelEvalMetrics: {} ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ( CheckLoss, Checkpoint, ComputeNorm, MixedPrecision, ModelEvalMetrics, TrainingLoop, ) from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model as LLaMA3 trainer = Trainer( backend=cstorch.backend("CSX", ...), model=lambda: LLaMA3(...), optimizer=lambda model: cstorch.optim.AdamW(...), schedulers=[...], precision=MixedPrecision(...), loop=TrainingLoop(...), checkpoint=Checkpoint(...), callbacks=[ ComputeNorm(), CheckLoss(), ModelEvalMetrics(), ], ) ... ``` ### Configure Loggers To keep track of the progress of our run, let’s also employ the use of the progress logger as well as the TensorBoard logger. * YAML: To configure these loggers, you can specify the following to the [loggers](../../model-zoo/trainer-configuration-overview) key. * Python: To configure these loggers, you can construct the following and pass them to the trainer. ```yaml YAML theme={null} trainer: init: backend: # CSX ... model: # llama ... optimizer: # AdamW ... schedulers: # CosineDecayLR ... precision: # DLS ... loop: ... checkpoint: ... callbacks: ... loggers: - ProgressLogger: {} - TensorBoardLogger: {} ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ( Checkpoint, MixedPrecision, TrainingLoop, ) from cerebras.modelzoo.trainer.loggers import ( ProgessLogger, TensorBoardLogger, ) from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model as LLaMA3 trainer = Trainer( backend=cstorch.backend("CSX", ...), model=lambda: LLaMA3(...), optimizer=lambda model: cstorch.optim.AdamW(...), schedulers=[...], precision=MixedPrecision(...), loop=TrainingLoop(...), checkpoint=Checkpoint(...), callbacks=[...], loggers=[ ProgessLogger(), TensorBoardLogger(), ], ) ... ``` ### Reproducibility In order to make the pretraining run reproducible, you must set the Trainer’s seed. * YAML: You can do this by specifying the \[seed]\(/model-zoo/trainer-configuration-overview key. * Python: You can do this by specifying the seed argument to the Trainer’s constructor as follows. ```Tab YAML theme={null} trainer: init: backend: # CSX ... model: # llama ... optimizer: # AdamW ... schedulers: # CosineDecayLR ... precision: # DLS ... loop: ... checkpoint: ... callbacks: ... loggers: ... seed: 2024 ... ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ( Checkpoint, MixedPrecision, TrainingLoop, ) from cerebras.modelzoo.trainer.loggers import ( ProgessLogger, TensorBoardLogger, ) from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model as LLaMA3 trainer = Trainer( backend=cstorch.backend("CSX", ...), model=lambda: LLaMA3(...), optimizer=lambda model: cstorch.optim.AdamW(...), schedulers=[...], precision=MixedPrecision(...), loop=TrainingLoop(...), checkpoint=Checkpoint(...), callbacks=[...], loggers=[...], seed=2024, ) ... ``` > [!NOTE] > > Setting different seeds across different runs of the same model may cause multiple compiles. ### Configure Dataloaders Now that you’ve constructed the `Trainer` object, you’re almost ready to start the pretraining run. One of the only things left to do is to configure the training and validation dataloaders you’ll be using. * YAML: To configure the training and validation dataloaders, you can specify the following to the \[train\_dataloader]\(/model-zoo/trainer-configuration-overview key). * Python: To configure the training and validation dataloaders, you can construct [`DataLoader`](https://training-api.cerebras.ai/en/latest/cs-torch/cerebras-pytorch-api/cerebras-pytorch-optim#cerebras.pytorch.utils.data.DataLoader "cerebras.pytorch.utils.data.DataLoader") objects and pass them into the Trainer’s [`fit`](https://training-api.cerebras.ai/en/latest/model-zoo/api/trainer-api#cerebras.modelzoo.Trainer.fit "cerebras.modelzoo.Trainer.fit") method as follows. ```yaml YAML theme={null} trainer: init: ... fit: train_dataloader: data_processor: GptHDF5MapDataProcessor data_dir: "/data/llama_v3_dataset_vocab128256/train" batch_size: 80 shuffle: False shuffle_seed: 1337 num_workers: 8 prefetch_factor: 10 persistent_workers: True # Important to avoid seeding at each epoch val_dataloader: - data_processor: GptHDF5MapDataProcessor data_dir: "/data/llama_v3_dataset_vocab128256/val" batch_size: 80 shuffle: False shuffle_seed: 1337 num_workers: 8 prefetch_factor: 10 persistent_workers: True # Important to avoid seeding at each epoch ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer(...) trainer.fit( train_dataloader=cstorch.utils.data.DataLoader( registry.get_data_processor("GptHDF5MapDataProcessor"), data_dir="/data/llama_v3_dataset_vocab128256/train", batch_size=80, shuffle=False, shuffle_seed=1337, num_workers=8, prefetch_factor=10, persistent_workers=True, # Important to avoid seeding at each epoch ), val_dataloader=[ cstorch.utils.data.DataLoader( registry.get_data_processor("GptHDF5MapDataProcessor"), data_dir="/data/llama_v3_dataset_vocab128256/val", batch_size=80, shuffle=False, shuffle_seed=1337, num_workers=8, prefetch_factor=10, persistent_workers=True, # Important to avoid seeding at each epoch ), ] ) ``` As can be seen, the specification of the training and validation dataloaders are very similar. The only difference is that you have the option of specifying multiple validation dataloaders to run validation over multiple datasets. > [!NOTE] > > Please make sure to change the `data_dir` arguments to point to the actual directories containing the data. ### Putting It All Together That is all there is to configuring the pretraining run! Let’s take a moment to step back and look at the full configuration that you’ve put together thus far. ```yaml YAML theme={null} trainer: init: backend: backend_type: CSX cluster_config: num_csx: 16 seed: 2024 model: # Embedding vocab_size: 128256 hidden_size: 4096 position_embedding_type: "rotary" pos_scaling_factor: 1.0 rope_theta: 500000.0 rotary_dim: 128 share_embedding_weights: false max_position_embeddings: 8192 embedding_dropout_rate: 0.0 embedding_layer_norm: false # Decoder num_hidden_layers: 32 dropout_rate: 0.0 layer_norm_epsilon: 1.0e-5 norm_type: "rmsnorm" # Decoder - Attention num_heads: 32 attention_type: "scaled_dot_product" attention_module: "multiquery_attention" attention_dropout_rate: 0.0 use_projection_bias_in_attention: false use_ffn_bias_in_attention: false extra_attention_params: num_kv_groups: 8 # Decoder - ffn filter_size: 14336 nonlinearity: "swiglu" use_ffn_bias: false # Task-specific use_bias_in_output: false loss_scaling: "num_tokens" loss_weight: 1.0 # Initializer initializer_range: 0.02 # Cerebras parameters mixed_precision: True fp16_type: "cbfloat16" optimizer: AdamW: betas: [0.9, 0.95] correct_bias: True weight_decay: 0.1 schedulers: - CosineDecayLR: initial_learning_rate: 3.0e-5 end_learning_rate: 3.0e-6 total_iters: 528 precision: fp16_type: cbfloat16 loss_scaling_factor: dynamic max_gradient_norm: 1.0 loop: num_steps: 10000 eval_frequency: 1000 eval_steps: 1000 checkpoint: steps: 1000 callbacks: - ComputeNorm: {} - CheckLoss: {} - ModelEvalMetrics: {} loggers: - ProgressLogger: {} - TensorBoardLogger: {} fit: train_dataloader: data_processor: GptHDF5MapDataProcessor data_dir: "/data/llama_v3_dataset_vocab128256/train" batch_size: 80 shuffle: False shuffle_seed: 1337 num_workers: 8 prefetch_factor: 10 persistent_workers: True # Important to avoid seeding at each epoch val_dataloader: - data_processor: GptHDF5MapDataProcessor data_dir: "/data/llama_v3_dataset_vocab128256/val" batch_size: 80 shuffle: False shuffle_seed: 1337 num_workers: 8 prefetch_factor: 10 persistent_workers: True # Important to avoid seeding at each epoch ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ( CheckLoss, Checkpoint, ComputeNorm, MixedPrecision, ModelEvalMetrics, TrainingLoop, ) from cerebras.modelzoo.trainer.loggers import ( ProgessLogger, TensorBoardLogger, ) from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model as LLaMA3 trainer = Trainer( backend=cstorch.backend( backend_type="CSX", cluster_config=cstorch.distributed.ClusterConfig( num_csx=16, ), ), seed=2024, model=lambda: LLaMA3( # Embedding vocab_size=128256, hidden_size=4096, position_embedding_type="rotary", pos_scaling_factor=1.0, rope_theta=500000.0, rotary_dim=128, share_embedding_weights=False, max_position_embeddings=8192, embedding_dropout_rate=0.0, embedding_layer_norm=False, # Decoder num_hidden_layers=32, dropout_rate=0.0, layer_norm_epsilon=1.0e-5, norm_type="rmsnorm", # Decoder - Attention num_heads=32, attention_type="scaled_dot_product", attention_module="multiquery_attention", attention_dropout_rate=0.0, use_projection_bias_in_attention=False, use_ffn_bias_in_attention=False, extra_attention_params=dict( num_kv_groups=8, ), # Decoder - ffn filter_size=14336, nonlinearity="swiglu", use_ffn_bias=False, # Task-specific use_bias_in_output=False, loss_scaling="num_tokens", loss_weight=1.0, # Initializer initializer_range=0.02, # Cerebras parameters mixed_precision=True, fp16_type="cbfloat16", ), optimizer=lambda model: cstorch.optim.AdamW( model.parameters(), lr=0.01, # This is a placeholder betas=[0.9, 0.95], correct_bias=True, weight_decay: 0.1, ), schedulers=[ lambda optimizer: cstorch.optim.lr_scheduler.CosineDecayLR( initial_learning_rate=3.0e-5, end_learning_rate=3.0e-6, total_iters=528, ) ], precision=MixedPrecision( fp16_type="cbfloat16", loss_scaling_factor="dynamic", max_gradient_norm=1.0, ), loop=TrainingLoop( num_steps=10000, eval_frequency=1000, eval_steps=1000, ), checkpoint=Checkpoint(steps=1000), callbacks=[ ComputeNorm(), CheckLoss(), ModelEvalMetrics(), ], loggers=[ ProgessLogger(), TensorBoardLogger(), ], ) trainer.fit( train_dataloader=cstorch.utils.data.DataLoader( registry.get_data_processor("GptHDF5MapDataProcessor"), data_dir="/data/llama_v3_dataset_vocab128256/train", batch_size=80, shuffle=False, shuffle_seed=1337, num_workers=8, prefetch_factor=10, persistent_workers=True, # Important to avoid seeding at each epoch ), val_dataloader=[ cstorch.utils.data.DataLoader( registry.get_data_processor("GptHDF5MapDataProcessor"), data_dir="/data/llama_v3_dataset_vocab128256/val", batch_size=80, shuffle=False, shuffle_seed=1337, num_workers=8, prefetch_factor=10, persistent_workers=True, # Important to avoid seeding at each epoch ), ] ) ``` ## Start Pretraining Now that you have a fully configured Trainer, all there is to do now is to kick off the run and start pretraining. * YAML: Let’s assume that the YAML configuration that you put together above is written to a file called `./pretrain_llama_8b.yaml`. To run pretraining, use the CLI command. * Python: Let’s assume that the python code that you put together above is written to a file called `./pretrain_llama_8b.py`. To run pretraining, execute that python script. ```bash YAML theme={null} cszoo fit ./pretrain_llama_8b.yaml ``` ```python Python theme={null} python ./pretrain_llama_8b.py ``` ## Monitor the Run Once compilation finishes and the Wafer-Scale Cluster is programmed for execution, you should start seeing progress logs that look like ``` | Train Device=CSX, Step=1, Loss=1.39258, Rate=16.30 samples/sec, GlobalRate=16.30 samples/sec | Train Device=CSX, Step=2, Loss=1.40430, Rate=20.40 samples/sec, GlobalRate=19.13 samples/sec | Train Device=CSX, Step=3, Loss=1.38086, Rate=21.93 samples/sec, GlobalRate=20.25 samples/sec | Train Device=CSX, Step=4, Loss=1.41211, Rate=22.45 samples/sec, GlobalRate=20.84 samples/sec | Train Device=CSX, Step=5, Loss=1.35352, Rate=22.57 samples/sec, GlobalRate=21.17 samples/sec | Train Device=CSX, Step=6, Loss=1.38477, Rate=22.54 samples/sec, GlobalRate=21.39 samples/sec | Train Device=CSX, Step=7, Loss=1.39258, Rate=22.52 samples/sec, GlobalRate=21.54 samples/sec | Train Device=CSX, Step=8, Loss=1.37695, Rate=22.44 samples/sec, GlobalRate=21.64 samples/sec | Train Device=CSX, Step=9, Loss=1.40234, Rate=22.33 samples/sec, GlobalRate=21.71 samples/sec | Train Device=CSX, Step=10, Loss=1.38281, Rate=22.38 samples/sec, GlobalRate=21.78 samples/sec | Train Device=CSX, Step=11, Loss=1.39453, Rate=21.32 samples/sec, GlobalRate=21.67 samples/sec | Train Device=CSX, Step=12, Loss=1.39844, Rate=21.72 samples/sec, GlobalRate=21.69 samples/sec | Train Device=CSX, Step=13, Loss=1.38672, Rate=21.88 samples/sec, GlobalRate=21.71 samples/sec | Train Device=CSX, Step=14, Loss=1.34961, Rate=21.91 samples/sec, GlobalRate=21.73 samples/sec | Train Device=CSX, Step=15, Loss=1.33203, Rate=21.88 samples/sec, GlobalRate=21.74 samples/sec | Train Device=CSX, Step=16, Loss=1.33008, Rate=21.91 samples/sec, GlobalRate=21.75 samples/sec | Train Device=CSX, Step=17, Loss=1.33984, Rate=21.88 samples/sec, GlobalRate=21.76 samples/sec | Train Device=CSX, Step=18, Loss=1.31250, Rate=21.88 samples/sec, GlobalRate=21.76 samples/sec | Train Device=CSX, Step=19, Loss=1.36133, Rate=21.91 samples/sec, GlobalRate=21.77 samples/sec | Train Device=CSX, Step=20, Loss=1.30664, Rate=23.15 samples/sec, GlobalRate=21.87 samples/sec | Train Device=CSX, Step=21, Loss=1.30078, Rate=22.52 samples/sec, GlobalRate=21.88 samples/sec | Train Device=CSX, Step=22, Loss=1.31250, Rate=22.23 samples/sec, GlobalRate=21.89 samples/sec | Train Device=CSX, Step=23, Loss=1.30664, Rate=21.10 samples/sec, GlobalRate=21.82 samples/sec | Train Device=CSX, Step=24, Loss=1.30469, Rate=22.73 samples/sec, GlobalRate=21.90 samples/sec | Train Device=CSX, Step=25, Loss=1.28906, Rate=21.42 samples/sec, GlobalRate=21.84 samples/sec ... | Eval Device=CSX, GlobalStep=1000, Batch=1, Loss=1.21875, Rate=21.47 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=2, Loss=1.24219, Rate=22.65 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=3, Loss=1.26562, Rate=22.06 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=4, Loss=1.25195, Rate=21.90 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=5, Loss=1.27539, Rate=21.80 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=6, Loss=1.23047, Rate=21.79 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=7, Loss=1.22852, Rate=20.72 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=8, Loss=1.27734, Rate=21.24 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=9, Loss=1.23633, Rate=22.57 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=10, Loss=1.27930, Rate=22.10 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=11, Loss=1.23438, Rate=20.86 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=12, Loss=1.24609, Rate=21.31 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=13, Loss=1.23633, Rate=21.47 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=14, Loss=1.23633, Rate=21.48 samples/sec, GlobalRates=21.66 samples/sec | Eval Device=CSX, GlobalStep=1000, Batch=15, Loss=1.21680, Rate=22.66 samples/sec, GlobalRates=21.66 samples/sec ... ``` > [!NOTE] > > The performance numbers that you get will vary depending on how many Cerebras systems you are using and which generation systems you are using. If you open up the TensorBoard you can more closely monitor the run be observing the trends in the graphs of the various logged metrics. ``` tensorboard --bind_all --logdir="./model_dir" ``` ![tensorboard](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/LLaMA3_8B_tensorboard.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=3b517b5fd5d8ab6540a5837f40d1f714) As can be seen above, the screenshots were taken at around step 5800. At this point you can observe that so far, the run seems to progressing well. The losses appear to be trending downwards and the model wise gradient norms don’t appear overly abnormal. ## Porting the Model to Hugging Face Once the pretraining run has finished, you can port the model and checkpoint to Hugging Face. To learn more about how to do this, see [Port a trained and fine-tuned model to Hugging Face](../../model-zoo/migration/port-a-trained-and-fine-tuned-model-to-hugging-face). ## Conclusion With that, you have completed your first pretraining run with validation on the Cerebras Wafer-Scale Cluster using the ModelZoo Trainer! By now, you should understand how to write your own Trainer configuration and how to kick off a training job on the Cerebras Wafer-Scale Cluster. You can now take this knowledge and pre-train your very own model. # Quickstart: Preprocess Your Data Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/core-workflows/quickstart-guide-for-data-preprocessing Learn how to preprocess text-only and multimodal datasets into HDF5 format for pretraining and fine-tuning. ## Before You Begin Before you can pretrain or fine-tune your model, preprocess your text-only or multimodal data into HDF5 format for the Cerebras platform. You will: * Set up your data directory * Prepare your config file * Run the preprocessing script * Visualize the preprocessed data Input files should be in one of the following formats: * `.jsonl`, `.json.gz`, `.jsonl.zst`, `.jsonl.zst.tar` * `.parquet` * `.txt` * `.fasta` ## Set Up Your Data Directory Place your raw data in a directory. If processing multimodal data, set up an image directory as well. You'll need to supply these paths in your config file. If you're using a HuggingFace dataset, note the name of the dataset. Learn more about using HuggingFace data [here](../model-zoo/components/data-preprocessing/data-preprocessing#setup-section). > [!WARNING] > > When using the Hugging Face CLI to download a dataset, you may encounter the following error: > > `KeyError: 'tags'` > > This issue occurs due to an outdated version of the `huggingface_hub` package. To resolve it, update the package by running: > > `pip install --upgrade huggingface_hub==0.26.1` ## Prepare Your Config File Your config file contains three sections: `setup`, `processing`, and `dataset`. > [!TIP] > > View example configs for various use cases [here](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/data_preparation/data_preprocessing/configs). Each section is broken down below with examples for different data types. ### Setup The **setup** section is where you set the path to your data, the mode (pretraining or fine-tuning), and other key flags. > [!TIP] > > Learn more about additional Setup flags [here](../../model-zoo/components/data-preprocessing/data-preprocessing#setup-section). Use the tabs to see examples for different data types: ```yaml Text-Only Data theme={null} setup: data: source: "" #local dir or HuggingFace dataset name type: "local" #set to "huggingface" to use HuggingFace data split: "test" cache_dir: "path/to/cache_dir" # other parameters accepted by HuggingFace ``load_dataset`` API... mode: "pretraining" #or "finetuning" output_dir: "./output/dir/here/" processes: 1 #desired number of CPU cores, set to 0 for default number of cores available ``` ```yaml Multimodal Data theme={null} setup: data: source: "/path/to/local/dataset" type: "local" image_dir: "/path/to/image_dir" mode: "finetuning" output_dir: "./output/dir/here/" processes: 1 ``` ### Processing The **processing** section is where you define which tokenizer and read hook you want to use. > [!TIP] > > * There are a variety of read hooks available and each one processes data differently, preparing it for specific machine learning tasks. Learn more about read hooks [here](https://cerebras-training.mintlify.app/model-zoo/components/data-preprocessing/read-hooks). > * Similarly, there are a variety of tokenizers available. Learn more about how to initialize different tokenizers [here](../../model-zoo/components/data-preprocessing/data-preprocessing#tokenizer-initialization). ```yaml Text-Only Data theme={null} processing: huggingface_tokenizer: "bert-base-uncased" tokenizer_params: param1: value1 param2: value2 read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks.text_read_hook" read_hook_kwargs: text_key: "text" resume_from_checkpoint: False max_seq_length: 2048 read_chunk_size: 1024 write_chunk_size: 1024 shuffle: False shuffle_seed: 0 ftfy_normalizer: NFC use_ftfy: False wikitext_detokenize: False ``` ```yaml Multimodal Data theme={null} processing: custom_tokenizer: cerebras.modelzoo.data_preparation.data_preprocessing.custom_tokenizer_example.CustomLlama3Tokenizer:CustomLlama3Tokenizer tokenizer_params: pretrained_model_name_or_path: "meta-llama/Meta-Llama-3-8B-Instruct" token: "" read_hook: "cerebras.modelzoo.data_preparation.data_preprocessing.hooks.finetuning_llava_hook_prompt_completion" read_hook_kwargs: multi_turn_key: "conversation" multi_turn_role_key : "from" multi_turn_content_key: "value" image_key: "" image_token: "" phase: 1 resume_from_checkpoint: False max_seq_length: 2048 read_chunk_size: 1024 write_chunk_size: 1024 shuffle: False shuffle_seed: 0 ftfy_normalizer: NFC use_ftfy: False wikitext_detokenize: False ``` ### Dataset The **dataset** section is where you can set additional token generator parameters. > [!TIP] > > Learn more about additional dataset parameters [here](https://cerebras-training.mintlify.app/model-zoo/components/data-preprocessing/data-preprocessing#dataset-parameters). ```yaml Text-Only Data theme={null} dataset: use_vsl: False pack_sequences: True ``` ```yaml Multimodal Data theme={null} dataset: is_multimodal: True use_vsl: False ``` ## Run the Preprocessing Script Run the following command with the path to your config file: ```bash theme={null} cszoo data_preprocess run --config /path/to/configuration/file ``` ## Visualize Your Data This tool visualizes preprocessed data efficiently and in an organized fashion, allowing for easy debugging and error-catching in the output data. You can supply other arguments (listed below) if needed. Run the following command: `python launch_tokenflow.py --output_dir  ` In your terminal, you will see a url like [`http://172.31.48.239:5000.`](http://172.31.48.239:5000.) Copy and paste this into your browser to launch [TokenFlow](../../model-zoo/components/data-preprocessing/visualization-and-debugging), a tool for interactively visualizing whether loss and attention masks were applied correctly: ![](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/getting-started/tokenflow_updated.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=8abdefa3a1e8fde7e748f7de5b87daf4) > [accordion] Arguments > > * `output_dir`: Contains the file(s) you can view in the GUI. *\[Required]* > * `data_params`: Location of the data\_params.json file for the preprocessed dataset. *\[Optional]* > * `port`: Use this to specify a different port for the flask server. *\[Optional, default=5000]* ## Output There are 4 sections in the visualization output. `input_strings` and `label_strings` are converted tokens from `input_ids` and `labels` respectively. The tokens in the string sections are highlighted in green when the loss weight is greater than zero for that specific token. Similarly, the tokens are highlighted in red when their attention mask is set to zero. For multimodal datasets, hovering over the image pad tokens also displays the corresponding image in the popup window. > [!TIP] > > Learn more about visualization and debugging [here](../../model-zoo/components/data-preprocessing/visualization-and-debugging). ## What's Next? Depending on your goals, check out our [Pretraining](../../getting-started/pre-train-your-first-model) or [Finetuning](../../getting-started/fine-tune-your-first-model) quickstart guides. # Summarize Scalars And Tensors Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/core-workflows/summarize-scalars-and-tensors On this page, you’ll learn how to track various values of interest during a run. More specifically, you will learn how to summarize various tensors in a PyTorch model and inspect them during or after a run. By the end, you should be comfortable visualizing tensors and scalars in a run for the model of your choice. ## Prerequisites * You must have installed the Cerebras Model Zoo (click [here](../../getting-started/setup-and-installation) if you haven’t). * You must be familiar with the [Trainer](../../model-zoo/trainer-overview) and [YAML format](../../model-zoo/trainer-configuration-overview) ## Configuring the Trainer To enable summaries, a `TensorBoardLogger` which is required for summaries to be written. ```yaml YAML theme={null} trainer: init: loggers: - TensorBoardLogger: {} ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.loggers import TensorBoardLogger trainer = Trainer( ..., loggers=[TensorBoardLogger()], ) ``` ## Scalar Summaries ### Motivation It is often useful to visualize various scalar values during training. This may include scalar values such as learning rate, gradient norms, etc. For this, we provide the `summarize_scalar` API which allows to summarize scalar model tensors. These summaries are written to Tensorboard events files and can be visualized using Tensorboard. ### How to use scalar summaries The scalar summary API is available as part of the `cerebras.modelzoo.trainer` package. To summarize a scalar tensor `S`, add the following statement to the model definition code: ```python theme={null} from cerebras.modelzoo.trainer import summarize_scalar summarize_scalar("my_scalar_tensor", S) ``` During training, the value of `S` will be periodically written to the Tensorboard events file and can be visualized in TensorBoard. ## Important considerations * If the [`Trainer`](../../model-zoo/trainer-overview) is not configured with a [TensorBoardLogger](https://docs.cerebras.net/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.loggers.html#cerebras.modelzoo.trainer.loggers.TensorBoardLogger) callback, this method is a no-op and no summaries will be written. ## Tensor Summaries ### Motivation In the section above, we described how to summarize scalar values, which can be visualized in TensorBoard. However, there are cases where it is desirable to summarize arbitrary tensor shapes. Since TensorBoard only supports visualizing scalar summaries, we provide a separate API, which is very similar to `summarize_scalar` API, but for summarizing tensors of arbitrary shapes. ### How to use tensor summaries The tensor summary API is available as part of the `cerebras.modelzoo.trainer` package. To summarize a tensor `T`, add the following statement to the model definition code: ```python theme={null} from cerebras.modelzoo.trainer import summarize_tensor summarize_tensor("my_tensor", T) ``` Under the hood, we mark the provided tensor as an output of the graph and fetch its value at every log step (similar to losses and other scalar summaries). This value is then written out to a file and can be later retrieved through the [`SummaryReader`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.utils.tensorboard.SummaryReader) API (see below). Here’s a simple example where we’d like to summarize the input features and last layer’s logits of a fully connected network: ```python theme={null} from cerebras.modelzoo.trainer import summarize_tensor class FC(nn.Module): def forward(self, features): summarize_tensor("features", features) logits = self.fc_layer(features) summarize_tensor("last_layer_logits", logits) return logits ``` To retrieve the saved values of these tensors during or after a run, use the [`SummaryReader`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.utils.tensorboard.SummaryReader) API which supports listing all available tensor names and fetching a tensor by name for a given step. [`SummaryReader`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.utils.tensorboard.SummaryReader) object takes as input a single argument denoting the path to a Tensorboard events file or a directory containing Tensorboard events files. Location of tensor summaries are inferred from these events files as there is a one-to-one mapping from Tensorboard events files and tensor summary directories. In the example above, we added summaries for `features` and `last_layer_logits`. We can then use the [`SummaryReader`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#cerebras.pytorch.utils.tensorboard.SummaryReader) API to load the summarized values of these tensors at a given step: ```python theme={null} >>> import cerebras.pytorch as cstorch >>> reader = cstorch.utils.tensorboard.SummaryReader("model_dir") >>> reader.tensor_names() # Grab all tensor summary names ['features', 'last_layer_logits'] >>> reader.read_tensor("features", 2) # Load tensor "features" from step 2 TensorDescriptor(step=2, tensor=tensor([[2, 4], [6, 8]]), utctime='2023-02-07T05:45:29.017264') >>> reader.read_tensor("non_existing", 100) # Load a non-existing tensor WARNING:root:No tensor with name non_existing has been summarized at step 100 ``` `SummaryReader.read_tensor()` returns one or more `TensorDescriptor` objects. `TensorDescriptor` is a POD structure which holds: * `step`: The step at which this tensor was summarized. * `utctime`: The UTC time at which the value was saved. * `tensor`: The summarized value. Scalar summaries can be read in the same way. ### Limitations Adding tensor summaries may change how the graph is lowered and can create a different compile. This is because marking a tensor as an output may prevent it from being pruned out in certain operation fusions. From an overall computation standpoint, however, the graphs should be identical. The only difference is how the computation is represented. ## Conclusion The ability to summarize scalars and tensors in a PyTorch model offers invaluable insights into the training process, allowing for the tracking and visualization of various values of interest. By leveraging the `SummaryWriter` and `DataExecutor` classes, along with the `summarize_scalar` and `summarize_tensor` APIs, users can effectively log and monitor key metrics and tensor values throughout the training lifecycle. These summaries not only aid in the immediate analysis and debugging of models but also facilitate long-term monitoring and evaluation of model performance over time. With the added functionality to retrieve and inspect these summarized values post-run, practitioners are equipped with a comprehensive toolset to optimize and refine their models, enhancing the overall efficiency and effectiveness of their training workflows in PyTorch. # Converter Tool Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/migration/convert-checkpoints-and-model-configs/convert-checkpoints-and-model-configs Learn how to convert checkpoints and config files between Model Zoo and other external code repositories using our converter tool. To convert model implementations between Model Zoo and other external code repositories, such as Hugging Face, use the Model Zoo CLI's `checkpoint` converter tool. Use the tool to: * Convert a pretrained checkpoint from an external repo to Cerebras format for continued training on CS systems. * Export a model trained in the Cerebras ecosystem to Hugging Face for inference elsewhere. * Update older Cerebras checkpoints to work with newer Model Zoo releases. ## Prerequisites Make sure you've completed [setup and installation](../rel-2.5.0/getting-started/setup-and-installation). ## Commands ```bash theme={null} $ cszoo checkpoint --help usage: cszoo checkpoint [-h] {info,delete,copy,move,diff,convert,convert-config,list-converters,list} ... positional arguments: {info,delete,copy,move,diff,convert,convert-config,list-converters,list} info Gives a high level summary of a checkpoint. delete Delete a checkpoint copy Copy a checkpoint move Move a checkpoint. diff Diff two checkpoints. convert Convert a checkpoint between CS and HuggingFace or across CS releases. convert-config Convert a config between CS and HuggingFace or across CS releases. list-converters List available converters. ``` ## Support and Limitations * Currently, the `convert` argument supports conversion between Cerebras Model Zoo and Hugging Face implementations. If you have a separate, custom checkpoint format you would like to convert to, contact Cerebras for assistance. * To update checkpoints that are multiple versions behind, incrementally run conversion through the intermediate releases (e.g., 1.9 -> 2.0 -> 2.1 -> 2.2). A list of supported converters can be found on this page, below. A checkpoint from a previous release must first be “fixed” to be 2.1 compatible, prior to conversion. See [Upgrading Checkpoints from Previous Versions](#upgrading-checkpoints-from-previous-versions) for more information. * If you plan to convert a Cerebras Model Zoo model to another repository, we strongly recommend running a config conversion first using the `convert-config` argument before starting training. This helps you verify whether your model can be successfully adapted to another format. Keep in mind that other repositories may not support the same level of flexibility as the Cerebras Model Zoo and may not accommodate certain model modifications. For instance, Hugging Face’s NLP models have fixed positional embedding implementations, which prevent adding ALiBi to a LLaMA model. ## Models Supported The following is a list of models supported by the tool: | | | | | - | - | - | | bert | bert-sequence-classifier | bert-token-classifier | | bert-summarization | bert-q\&a | bloom | | bloom-headless | btlm | btlm-headless | | codegen | codegen-headless | code-llama | | code-llama-headless | dpo | dpr | | falcon | falcon-headless | flan-ul2 | | gpt2 | gpt2-headless | gpt2 with muP | | gptj | gptj-headless | gpt-neox | | gpt-neox-headless | jais | llama | | llama-headless | llamaV2 | llamaV2-headless | | llava | mpt | mpt-headless | | mistral | mistral-headless | octocoder | | octocoder-headless | roberta | santacoder | | santacoder-headless | sqlcoder | sqlcoder-headless | | starcoder | starcoder-headless | t5 | | transformer | ul2 | wizardcoder | | wizardcoder-headless | wizardlm | wizardlm-headless | ## Usage > [!NOTE] > > * Before using the converter, run the `list-converters` argument and read its output notes. The output specifies which model classes are being converted from and to, and highlights any important caveats. > > * Checkpoints that do not require model changes bewteen Cerebras releases still need to be converted to the correct release. There are checkpoint metadata conversions needed as well as config changes. 1. List all models/conversions that we support: ```bash theme={null} cszoo checkpoint list-converters ``` 2. To convert a config file only, use the following command: ```bash theme={null} cszoo checkpoint convert-config \ --model \ --src-fmt \ --tgt-fmt \ --output-dir \ ``` 3. To convert a checkpoint and its corresponding config, use the following command: ```bash theme={null} cszoo checkpoint convert \ --model \ --src-fmt \ --tgt-fmt \ --output-dir \ \ --config ``` To learn more about usage and optional parameters about a particular subcommand, pass the `-h` flag. For example: ```bash theme={null} cszoo checkpoint convert -h ``` > [!NOTE] > > `--src-fmt` and `--tgt-fmt` can be automatically inferred for CS checkpoints. Use `--src-fmt cs-auto` to detect the Cerebras version from the checkpoint (works on version 2.1+ checkpoints). Use `--tgt-fmt cs-current` to specify checkpoint conversion to the current release version. ## Examples ### Convert an Eleuther AI GPT-J 6B checkpoint with a model card to Cerebras Model Zoo Eleuther’s final GPT-J checkpoint can be accessed on Hugging Face at [EleutherAI/gpt-j-6B](https://huggingface.co/EleutherAI/gpt-j-6B). Rather than manually entering the values from the model architecture table into a config file and writing a script to convert their checkpoint, we can auto-generate these with a single command. First, we need to download the config and checkpoint files from the model card locally: ```bash theme={null} mkdir opensource_checkpoints wget -P opensource_checkpoints https://huggingface.co/EleutherAI/gpt-j-6B/raw/main/config.json wget -P opensource_checkpoints https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/pytorch_model.bin ``` > [!NOTE] > > Use the appropriate https link when downloading files from Hugging Face model card pages. Use the path that contains `…/raw/…` for config files. Use the path that contains `…/resolve/…` for checkpoint files. Hugging Face configs contain the `architecture` property, which specifies the class with which the checkpoint was generated. According to `config.json`, the HF checkpoint is from the `GPTJForCausalLM` class. Using this information, we can use the checkpoint converter tool’s `list` command to find the appropriate converter. In this case, we want to use the `gptj` model, with a source format of `hf`, and a target format of `cs-2.0`. Now to convert the config & checkpoint, run the following command: ```bash theme={null} cszoo checkpoint convert \ --model gptj \ --src-fmt hf \ --tgt-fmt cs-2.0 \ --output-dir opensource_checkpoints/ \ opensource_checkpoints/pytorch_model.bin \ --config opensource_checkpoints/config.json ``` This produces two files: * `opensource_checkpoints/pytorch_model_to_cs-2.0.mdl` * `opensource_checkpoints/config_to_cs-2.0.yaml` The output YAML config file contains the auto-generated `model` parameters from the Eleuther implementation. Before you can train/eval the model on the Cerebras cluster, add the `train_input`, `eval_input`, `optimizer`, and `runconfig` parameters to the YAML. Examples for these parameters can be found in the `configs/` folder for each model within Model Zoo. In this case, we can copy the missing information from `modelzoo/models/nlp/gptj/configs/params_gptj_6B.yaml` into `opensource_checkpoints/config_to_cs-2.0.yaml`. Make sure you modify the dataset paths under `train_input` and `eval_input` if they are stored elsewhere. ### Convert a Hugging Face model without a model card to Cerebras Model Zoo Not all pretrained checkpoints on Hugging Face have corresponding model card web pages. You can still download these checkpoints and configs to convert them into a Model Zoo compatible format. For example, Hugging Face has a [model card](https://huggingface.co/bert-base-uncased) for `BertForMaskedLM` accessible through the name `bert-base-uncased`. However, it doesn’t have a webpage for `BertForPreTraining`, which we’re interested in. We can manually get the config and checkpoint for this model as follows: ```bash theme={null} >>> from cerebras.modelzoo.models.nlp.bert.model import BertForPreTraining >>> model = BertForPreTraining.from_pretrained("bert-base-uncased") >>> model.save_pretrained("bert_checkpoint") ``` This saves two files: `bert_checkpoint/config.json` and `bert_checkpoint/pytorch_model.bin` Now that you have downloaded the required files, you can convert the checkpoints. Use the `--model bert` flag since the Hugging Face checkpoint is from the `BertForPreTraining` class. If you want to use another checkpoint from a different variant (such as a finetuning model), see the other `bert-` model converters. The final conversion command is: ```bash theme={null} cszoo checkpoint convert \ --model bert \ --src-fmt hf \ --tgt-fmt cs-2.0 \ bert_checkpoint/pytorch_model.bin \ --config bert_checkpoint/config.json ``` ### Convert a Cerebras Model Zoo GPT-2 checkpoint to Hugging Face Suppose you just finished training GPT-2 on CS and want to run the model within the Hugging Face ecosystem. In this example, the configuration file is saved at `model_dir/train/params_train.yaml` and the checkpoint (corresponding to step 10k) is at `model_dir/checkpoint_10000.mdl` To convert the Hugging Face, run the following command: ```bash theme={null} cszoo checkpoint convert \ --model gpt2 \ --src-fmt cs-2.0 \ --tgt-fmt hf \ model_dir/checkpoint_10000.mdl \ --config model_dir/train/params_train.yaml ``` Since the `--output-dir` flag is omitted, the two output files are saved to the same directories as the original files: * `model_dir/train/params_train_to_hf.json` * `model_dir/checkpoint_10000_to_hf.bin` ## YAML and Model Config Updates As our Model Zoo implementations evolve over time, the changes may sometimes break out-of-the-box compatibility when moving to a new release. To ensure that you can continue using your old checkpoints, we offer converters that allow you to “upgrade” configs and checkpoints when necessary. The section below covers conversions that are required when moving to a particular release. If a converter doesn’t exist, no explicit conversion is necessary. ### Release 2.2.0 In order to continue using your checkpoints & configs from release 2.1 in release 2.2.0+, you’ll need to upgrade them. See the example from the Release 2.1.0 section for additional details. ### Release 2.1.0 We made many updates to our model implementations and runner API. In order to continue using your checkpoints & configs from release 2.0 in release 2.1.0, upgrade them using the following command: ```bash theme={null} cszoo checkpoint convert \ --model \ --src-fmt cs-2.0 \ --tgt-fmt cs-2.1 \ --config ``` In the command above, `--model` should be the name of the model that you were training (for example `gpt2`). ### Release 2.0.2 #### Upgrading Checkpoints From Previous Versions For checkpoints pre-2.0, dataloader state files need to be converted to the dataloader checkpoint format for the new map and iterable dataloaders in Model Zoo in releases 2.0+. This allows for deterministic restart of the dataloader for model training jobs that move from releases prior to 2.0 to release 2.0+. The dataloader state conversion will automatically be done during checkpoint conversion if this is set in the config: ```yaml theme={null} cerebras: save_iter_state_path: ``` `save_iter_state_path` is the path to the directory containing data step file `data_iter_checkpoint_state_file_global` and worker checkpoint files of the format `data_iter_state_file_worker_*_step_*.txt`. **Streaming Conversion** In prior releases, conversion required both the input & output checkpoints to be stored in memory during conversion. This meant that large models required a prohibitively large amount of memory in order to perform conversion. In release 2.0.0, we introduce streaming conversion, which significantly reduces the peak memory usage by performing conversion incrementally. This is done by loading/saving one shard at a time for pickled checkpoints and loading/saving one tensor at a time for Cerebras H5 checkpoints. **Streaming conversion is enabled by default; you don’t need to make any changes to the command line arguments.** Thanks to this feature, you will now be able to convert massive checkpoints (e.g.: LLaMA 70B) on a small machine (\~10GB of RAM). **Upgrading LLaMA, Transformer, T5** To make it easier to control the type of normalization layer used by Model Zoo models, we have replaced the `use_rms_norm` and `use_biasless_norm` flags in the model configs to instead use `norm_type`. To continue using rel 1.9 checkpoints in rel 2.0, you’ll need to update the config to reflect this change. You can do this automatically using the config converter tool as follows: ```bash theme={null} cszoo checkpoint convert-config \ --model \ --src-fmt cs-1.9 \ --tgt-fmt cs-2.0 \ ``` In the command above, `--model` should be either `llama`, `t5`, or `transformer`, depending on which model you’re using (other models use the same configs as in 1.9, and as a result do not need to be upgraded). The config file path should point to the `train/params_train.yaml` file within your model directory. ### Release 1.9.1 All configs and checkpoints from release 1.8.0 can continue to be used in release 1.9.1 without any conversion. ### Release 1.8.0 **T5 / Vanilla Transformer** As described in the release notes, the behavior of the `use_pre_encoder_decoder_layer_norm` flag has been flipped. To continue using rel 1.7 checkpoints in rel 1.8, you’ll need to update the config to reflect this change. You can do this automatically using the config converter tool as follows: ```bash theme={null} cszoo checkpoint convert-config \ --model \ --src-fmt cs-1.7 \ --tgt-fmt cs-1.8 \ ``` In the command above, `--model` should be either `t5` or `transformer` depending on which model you are using. The config file path should point to the `train/params_train.yaml` file within your model directory. **BERT** As described in the release notes, we expanded the BERT model configurations to expose two additional parameters: `pooler_nonlinearity` and `mlm_nonlinearity`. Due to a change in the default value of the `mlm_nonlinearity` parameter, you will need to update the config when using a rel 1.7 checkpoint in rel 1.8. You can do this automatically using the config converter tool as follows: ```bash theme={null} cszoo checkpoint convert-config \ --model bert \ --src-fmt cs-1.7 \ --tgt-fmt cs-1.8 \ ``` The config file path should point to the `train/params_train.yaml` file within your model directory. # Convert CS Checkpoints for GPUs Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/migration/convert-checkpoints-and-model-configs/work-with-cerebras-checkpoints Learn how to work with Cerebras-format checkpoints, including how to load, convert, and reuse them in your training workflows. ## PyTorch Checkpoint Format Our large model-optimized checkpoint format is based off the standard [HDF5 file format](https://docs.h5py.org/en/stable/index.html). At a high-level, when saving a checkpoint, the Cerebras stack will take a PyTorch state dictionary, flatten it, and store it in an HDF5 file. For example, the following state dictionary is flattened and stored into the H5 file as follows: ```python theme={null} { "a": { "b": 0.1, "c": 0.001, }, "d": [0.1, 0.2, 0.3] } ``` Flattened H5: ```python theme={null} { "a.b": 0.1, "a.c": 0.001, "d.0": 0.1, "d.1": 0.2, "d.2": 0.3, } ``` A model/optimizer state dictionary can be saved in the new checkpoint format using the `cstorch.save` method: ```python theme={null} import cerebras.pytorch as cstorch ... state_dict = { "model": model.state_dict(), "optimizer": optimizer.state_dict(), } cstorch.save(state_dict, "path/to/checkpoint") ... ``` A checkpoint saved using the above can be loaded using the `cstorch.load` method: ```python theme={null} import cerebras.pytorch as cstorch ... state_dict = cstorch.load("path/to/checkpoint") model.load_state_dict(state_dict["model"]) optimizer.load_state_dict(state_dict["optimizer"]) ... ``` ### Convert to Pickle Format If using `cstorch.load` is not a sufficient solution for loading the checkpoint into memory, a simple conversion can be done to the pickle format: ```python theme={null} import torch import cerebras.pytorch as cstorch state_dict = cstorch.load("path/to/checkpoint") torch.save(state_dict, "path/to/new/checkpoint") ``` # Convert From Hugging Face Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/migration/port-a-hugging-face-model-to-cerebras-model-zoo Learn how to convert Hugging Face models to the Cerebras Model Zoo format, enabling seamless deployment and optimization on Cerebras's advanced hardware. This guide uses the `BertForPretraining` class as an example. You'll download the checkpoint and config files, convert the checkpoint, verify the output, and then use the newly converted model. ## Download Checkpoint and Config Files First, you need to download the model’s checkpoint and configuration files from Hugging Face. Here’s how you can do it for `BertForPreTraining`: ```python theme={null} from transformers import BertForPreTraining # Replace 'bert-base-uncased' with the model you are interested in model = BertForPreTraining.from_pretrained("bert-base-uncased") model.save_pretrained("bert_checkpoint") ``` This code will save two files in the `bert_checkpoint` directory: * config.json: The model’s configuration file. * pytorch\_model.bin: The model’s weights. ## Convert Checkpoint to Cerebras Format Now that you have the necessary files, you can convert them to a format compatible with the Cerebras Model Zoo. Use the provided conversion script in the Cerebras Model Zoo toolkit. Here’s the command: ```python theme={null} # Navigate to the directory containing the convert_checkpoint.py script cd /modelzoo/common/model_utils/ # Run the conversion python convert_checkpoint.py convert \ --model bert \ # Specify the model type --src-fmt hf \ # Source format (Hugging Face) --tgt-fmt cs-2.0 \ # Target format (Cerebras) bert_checkpoint/pytorch_model.bin \ # Input checkpoint file --config bert_checkpoint/config.json # Configuration file ``` Replace `` with the actual path to the Model Zoo directory on your system. ### Verify the Output After running the conversion script, check the `bert_checkpoint` directory for the output files: * `pytorch_model_to_cs-2.0.mdl`: The converted model checkpoint. * `config_to_cs-2.0.yaml`: The converted configuration file. ## Use the Converted Model With the converted files, you can now use the Cerebras Model Zoo tools and workflows to further train or deploy the model on Cerebras hardware. > [!NOTE] > > * If you’re converting a different model (not BERT), replace `--model bert` with the appropriate model flag. > > * If the model you’re converting has a specific variant or is a fine-tuning model, ensure you’re using the correct converter and flags as per the Cerebras documentation. # Convert to Hugging Face Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/migration/port-a-trained-and-fine-tuned-model-to-hugging-face Learn how to use the Model Zoo CLI to convert to Hugging Face. Once you have trained a language model on the cluster, you can port it to Hugging Face to generate outputs. For more information, refer to [Convert Checkpoints and Model Configs](../../model-zoo/migration/convert-checkpoints-and-model-configs/convert-checkpoints-and-model-configs). > [!NOTE] > > This guide uses an example from Spring 2023 with CerebrasGPT which uses release 1.8 (cs-1.8) as the source format. ## Procedure 1. To use the conversion tool, activate the Cerebras virtual environment and specify the following flags: | Flag | Description | | - | - | | `--model gpt2` | Model architecture the checkpoint corresponds to | | `--src-fmt cs-1.8` | the source format of the checkpoint corresponding to Cerebras Model Zoo(R1.8) | | `--tgt-fmt hf` | Target format of the checkpoint corresponding to Hugging Face | | `--config custom_config_GPT111M.yaml` | `yaml` file configuration used for training the model | | `--output-dir hf_dir_train_from_scratch_GPT111M` | Directory containing the output configuration and checkpoint | ```bash theme={null} cd $PARENT_CS source venv_cerebras_pt/bin/activate ``` ```bash theme={null} cszoo checkpoint convert \ --model gpt2 \ --src-fmt cs-1.8 \ --tgt-fmt hf \ --config custom_config_GPT111M.yaml \ --output-dir hf_dir_train_from_scratch_GPT111M \ train_from_scratch_GPT111M/checkpoint_10.mdl ``` 2. Convert the checkpoint obtained from fine-tuning “Cerebras-GPT 111M” included in the model directory finetune\_GPT111M. ```bash theme={null} cd $PARENT_CS source venv_cerebras_pt/bin/activate ``` ```bash theme={null} cszoo checkpoint convert \ --model gpt2 \ --src-fmt cs-1.8 \ --tgt-fmt hf \ --config custom_config_GPT111M.yaml \ --output-dir hf_dir_finetune_GPT111M \ finetune_GPT111M/checkpoint_10.mdl ``` 3. To facilitate importing the model in Hugging Face, modify the configuration file’s name to include gpt2 in it. ```bash theme={null} mv hf_dir_train_from_scratch_GPT111M/custom_config_GPT111M_to_hf.json hf_dir_train_from_scratch_GPT111M/config_to_hf_gpt2.json mv hf_dir_finetune_GPT111M/custom_config_GPT111M_to_hf.json hf_dir_finetune_GPT111M/config_to_gpt2.json ``` Now the trained models can be used with Hugging Face. 4. Create a Python virtual environment to use Hugging Face. Before you proceed, deactivate the CS virtual environment. ```bash theme={null} python -m venv hf_env ``` ```bash theme={null} source hf_env/bin/activate ``` ```bash theme={null} pip install 'transformers[torch]' ``` ```bash theme={null} python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('we love y ``` 5. Once you have set up the virtual environment, you can now generate outputs using Hugging Face. The tokenizer can be found in Cerebras-GPT-111M available in Hugging Face. Here is an example using the model trained from scratch: ```bash theme={null} python ``` ```python theme={null} Python 3.8.13 (default, Aug 16 2022, 12:16:29) [GCC 9.3.1 20200408 (Red Hat 9.3.1-2)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig >>> from transformers import pipeline >>> tokenizer = AutoTokenizer.from_pretrained("cerebras/Cerebras-GPT-111M") >>> config = AutoConfig.from_pretrained("./hf_dir_train_from_scratch_GPT111M/config_to_hf_gpt2.json") >>> model = AutoModelForCausalLM.from_pretrained(pretrained_model_name_or_path="./hf_dir_train_from_scratch_GPT111M/checkpoint_10_to_hf.bin", config = config) >>> text = "Generative AI is " >>> pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) >>> generated_text = pipe(text, max_length=50, do_sample=False, no_repeat_ngram_size=2)[0] Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. >>> print(generated_text['generated_text']) Generative AI is tossed separatist separatist,, separatist Fantasy, heading, Po, green, confession confession Po Po?!", 113, Pitch, counselormot newfound,ioch confession, Christopher, newfoundmotmot confessionrealDonaldTrump,Vict,icity confessionmot resear >>> exit() ``` Here is an example using the model **fine-tuned using Cerebras-GPT checkpoint:** ```python theme={null} Python 3.8.13 (default, Aug 16 2022, 12:16:29) [GCC 9.3.1 20200408 (Red Hat 9.3.1-2)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig >>> from transformers import pipeline >>> tokenizer = AutoTokenizer.from_pretrained("cerebras/Cerebras-GPT-111M") >>> config = AutoConfig.from_pretrained("./hf_dir_finetune_GPT111M/config_to_hf_gpt2.json") >>> model = AutoModelForCausalLM.from_pretrained("./hf_dir_finetune_GPT111M/checkpoint_10_to_hf.bin", config = config) >>> text = "Generative AI is " >>> pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) >>> generated_text = pipe(text, max_length=50, do_sample=False, no_repeat_ngram_size=2)[0] Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. >>> print(generated_text['generated_text']) Generative AI is The following is a list of the most common types of AI in the world. AI is the number of human AI classes in which the AI class is defined. The AI type is the number that the human >>> exit() ``` # Port Pytorch Models To Cerebras Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/migration/porting-pytorch-models-to-cerebras Learn how to convert existing PyTorch models to run on Cerebras systems. You'll set up the Cerebras environment, configure data processing, adapt the model architecture, and run training and evaluation scripts. Porting models to Cerebras offers significant benefits such as enhanced performance due to specialized hardware, scalability for large models, and efficient handling of extensive datasets. The [Cerebras Model Zoo](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/.) repository offers PyTorch-based reference implementations of well-known neural networks, including BERT, GPT-2, GPT-3, T5, and UNet. These implementations are organized in a modular fashion, dividing data preprocessing, the core model, and other execution-related functions. ## Before You Begin Before starting, ensure you meet the following prerequisites and requirements: * Familiarity with PyTorch and neural network architectures. * Access to Cerebras systems and the necessary permissions. * Basic understanding of YAML for configuration files. ## Pathways for Porting Models We offer two tailored pathways depending on the complexity of the task and your level of comfort: **1.** Straightforward approach: This pathway is ideal for those who wish to adapt existing models from the Cerebras Model Zoo. It involves making necessary changes to the model’s architecture or its data preprocessing components. This approach leverages the pre-built models and scripts available in the Model Zoo, minimizing the effort required to get started. **2.** Moderately complex pathway: This pathway is suited for users who intend to create new models and develop custom data preprocessing scripts. It involves starting with the robust foundation provided by the Cerebras Model Zoo and building upon it. This approach offers more flexibility and allows for extensive customization to meet specific needs. ## Customizing Models from the Cerebras Model Zoo If you intend to use models from the Cerebras Model Zoo and need to modify the model architecture or data preprocessing, it is recommended to start with the resources available in the Cerebras Model Zoo. This starting point allows you to make the necessary customizations to fit your specific requirements. This section guides users on adapting these pre-built models, which might involve changes to the model architecture or adjustments in data preprocessing. ### Example: Modifying a Dataloader The data loader is a crucial element that feeds data into the model for training and evaluation. By modifying the dataloader, users can customize how the data is processed, presented, or augmented before being used by the model. In this example, we focus on modifying the dataloader within the PyTorch implementation of FC\_MNIST from the Cerebras Model Zoo. The goal is to create a synthetic dataloader that will help assess the network’s performance with varying input sizes and class counts. #### Define the Data Loader Function In `data.py`, we’re going to define a function named `get_random_dataloader`: ```python theme={null} import torch import numpy as np def get_random_dataloader(input_params): num_classes = input_params.get("num_classes") num_examples = input_params.get("num_examples") batch_size = input_params.get("batch_size") seed = input_params.get("seed", 1) image_size = input_params.get("image_size", [1,28,28]) # Note: Cast the tensor to be of dtype `np.int32` when running on CS-X systems and to `np.int64` when running on cpus/gpus. np.random.seed(seed) image = np.random.random(size=[num_examples, ] + image_size).astype(np.float32) label = np.random.randint(low=0, high=num_classes, size=num_examples).astype(np.int32) dataset = torch.utils.data.TensorDataset( torch.from_numpy(image), torch.from_numpy(label) ) return torch.utils.data.DataLoader( dataset, batch_size=batch_size, ) def get_train_dataloader(params): return get_random_dataloader(params["train_input"]) def get_eval_dataloader(params): return get_random_dataloader(params["eval_input"]) ``` This function generates random images and labels, simulating a dataset for experiments. The key feature of this function is its configurability via the `params.yaml` file. #### Configuring the Dataloader In the `params.yaml`, we can specify several important parameters that will influence the behavior of our synthetic data loader: * `num_examples`: This parameter sets how many random images and labels the data loader should generate. * `batch_size`: This defines how many examples will be included in a single batch during the training or evaluation of the model. * `seed`: A seed for the random number generator ensures the reproducibility of our experiments by generating the same sequence of random images and labels for a given seed value. * `image_size`: This specifies the dimensions of the generated random images. * `num_classes`: This determines how many different classes the labels can take, which is crucial for classification tasks. By adjusting these parameters in the `params.yaml` file, we can tailor the behavior of the `get_random_dataloader` function to meet our specific experimental needs, allowing for a flexible and dynamic approach to evaluating the network’s performance under different conditions. ### Adapting the Model In `model.py`, change the fix number of classes to a parameter in the `params.yaml` file: ```python theme={null} class MNIST(nn.Module): def __init__(self, model_params): super().__init__() self.loss_fn = nn.NLLLoss() self.fc_layers = [] input_size = model_params.get("input_size",784) num_classes = model_params.get("num_classes",10) ... self.last_layer = nn.Linear(input_size, num_classes) ... ``` In `configs/params.yaml`, add the additional fields used in the dataloader and model definition. ## Developing New Models and Preprocessing Scripts ### Utilizing the Cerebras Run Function If you aim to create new models and data preprocessing scripts, we recommend beginning with the Cerebras Model Zoo’s shared foundation, specifically the `run` function. This approach allows you to utilize an established structure, streamlining the development process for your custom models and preprocessing routines. All PyTorch models in the Cerebras Model Zoo share a standard framework that facilitates running them on the Cerebras Systems (CS) platform or other hardware types like CPUs/GPUs. This framework handles the modifications required to compile and execute a model on a Cerebras cluster. It offers a unified training and evaluation interface, allowing users to integrate their models and data preprocessing scripts seamlessly. With this setup, users don’t need to make detailed code adjustments for compatibility with Cerebras systems. ### Porting a PyTorch Dense Neural Network for MNIST To utilize the `run` function effectively, ensure that the Cerebras Model Zoo repository, compatible with your target Cerebras cluster’s release, is installed. You can import the run function with the following code snippet: ```python theme={null} from cerebras.modelzoo.common.run_utils import run ``` Code related with run function lives inside the Cerebras Model Zoo and can be found in the [common](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/common) folder. The `run` function simplifies and organizes various aspects of your model’s workflow, including its implementation, data loading processes, hyperparameter settings, and overall execution. To effectively use the `run` function, you should have: 1. A params YAML file, which specifies the optimizers and the runtime configuration. 2. An implementation that encompasses: * The definition of your model. * Dataloaders that are responsible for both training and evaluation. #### Define Model To define the model architecture, the `run` function requires a callable class or function that takes as input a dictionary of params and returns a `torch.nn.Module` whose `forward` implementation returns a loss tensor. For example, let’s implement FC\_MNIST parametrized by the depth and the hidden size of the network. Let’s assume that the input size is 784 and the last output dimension is 10. We use `ReLU` as non linearity, and a negative log likelihood loss. In `model.py`: ```python theme={null} import torch import torch.nn as nn import torch.nn.functional as F class MNISTModel(nn.Module): def __init__(self, model_params): super().__init__() self.fc_layers = [] input_size = 784 # Depth is len(hidden_sizes) model_params["hidden_sizes"] = [ model_params["hidden_size"] ] * model_params["depth"] for hidden_size in model_params["hidden_sizes"]: fc_layer = nn.Linear(input_size, hidden_size) self.fc_layers.append(fc_layer) input_size = hidden_size self.fc_layers = nn.ModuleList(self.fc_layers) self.last_layer = nn.Linear(input_size, 10) self.nonlin = nn.ReLU() self.dropout = nn.Dropout(model_params["dropout"]) self.loss_fn = nn.NLLLoss() def forward(self, batch): inputs, targets = batch x = torch.flatten(inputs, 1) for fc_layer in self.fc_layers: x = fc_layer(x) x = self.nonlin(x) x = self.dropout(x) pred_logits = self.last_layer(x) outputs = F.log_softmax(pred_logits, dim=1) loss = self.loss_fn(outputs, targets) return loss ``` > [!NOTE] > > * The input to a `torch.nn.Module` object defined in the `run` function includes both the inputs and the labels to compute the loss. It is up to the model to extract the inputs and labels from the batch before using them. > > * The output of the model is expected to be the loss of that forward pass. #### Define Dataloaders To define the data loaders, the run function requires a callable (either class or function) that takes as input a dictionary of params, and returns a `torch.utils.data.DataLoader`. When running training, the `train_data_fn` must be provided. When running evaluation, the `eval_data_fn` must be provided. For example, to implement FC\_MNIST, we create two different functions for training and evaluation. We use `torchvision.datasets` functionality to download MNIST dataset. Each of these functions returns a `torch.utils.data.DataLoader`. In `data.py`: ```python theme={null} import torch from torchvision import datasets, transforms def get_train_dataloader(params): input_params = params["train_input"] batch_size = input_params.get("batch_size") dtype = torch.float16 if input_params["to_float16"] else torch.float32 shuffle = input_params["shuffle"] train_dataset = datasets.MNIST( input_params["data_dir"], train=True, download=True, transform=transforms.Compose( [ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)), transforms.Lambda( lambda x: torch.as_tensor(x, dtype=dtype) ), ] ), target_transform=transforms.Lambda( lambda x: torch.as_tensor(x, dtype=torch.int32) ), ) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=batch_size, drop_last=input_params["drop_last_batch"], shuffle=shuffle, num_workers=input_params.get("num_workers", 0), ) return train_loader def get_eval_dataloader(params): input_params = params["eval_input"] batch_size = input_params.get("batch_size") dtype = torch.float16 if input_params["to_float16"] else torch.float32 eval_dataset = datasets.MNIST( input_params["data_dir"], train=False, download=True, transform=transforms.Compose( [ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)), transforms.Lambda( lambda x: torch.as_tensor(x, dtype=dtype) ), ] ), target_transform=transforms.Lambda( lambda x: torch.as_tensor(x, dtype=torch.int32) ), ) eval_loader = torch.utils.data.DataLoader( eval_dataset, batch_size=batch_size, drop_last=input_params["drop_last_batch"], shuffle=False, num_workers=input_params.get("num_workers", 0), ) return eval_loader ``` #### Set Up the `run` Function The run function must be imported from [run\_utils.py](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/common/run_utils.py). Always remember to append the parent directory of the Cerebras Model Zoo repository in your local setup. All the input parameters of `run` function are callables that take a dictionary as input, called `params`. `params` is a dictionary containing all of the model and data parameters specified by the params YAML file of the model. | Parameter | Type | Notes | | - | - | - | | `model_fn` | `Callable[[dict], torch.nn.Module]` | Required. A callable that takes in a dictionary of parameters. Returns a `torch.nn.Module`. | | `train_data_fn` | `Callable[[dict], torch.utils.data.DataLoader]` | Required during training run. | | `eval_data_fn` | `Callable[[dict], torch.utils.data.DataLoader]` | Required during evaluation run. | | `default_params_fn` | `Callable[[dict], Optional[dict]]` | Optional. A callable that takes in a dictionary of parameters. Sets default parameters. | For the FC\_MNIST example, with all of the elements in place, now we import the run function from [modelzoo.common.run\_utils](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/common/run_utils.py). We append the parent directory of Cerebras Model Zoo. In `run.py`: ```python theme={null} import os import sys #Append path to parent directory of Cerebras ModelZoo Repository sys.path.append(os.path.join(os.path.dirname(__file__), "..")) from modelzoo.common.run_utils import run from data import ( get_train_dataloader, get_eval_dataloader, ) from model import MNISTModel def main(): run(MNISTModel, get_train_dataloader, get_eval_dataloader) if __name__ == '__main__': main() ``` #### Manage Common Params To avoid params replication between multiple similar experiments, the `run` function has an optional input parameter called `default_params_fn`. This parameter modifies the dictionary of the params YAML file, adding default values of unspecified params. Setting up a `default_params_fn` could be beneficial if the user is planning multiple experiments in which only a small subset of the params YAML file changes. The `default_params_fn` sets up the values shared in all of the experiments. The user can create different configuration YAML files to only address the changes between experiments. The `default_params_fn` should be a callable that takes in the `params` dictionary and returns a new dictionary. If the `default_params_fn` is omitted, the `params` dictionary will be used as is. #### Create Params YAML File At runtime, the `run` function requires a separate params YAML. This file is specified during execution with the flag `--params` in the command line. For example, this is the `params.yaml` file for the FC\_MNIST implementation. You can see both the [new YAML specification](../../model-zoo/trainer-configuration-overview) (since release 2.3.0) and the legacy YAML specification. > [!WARNING] > > Since release 2.3.0, the legacy YAML specification is deprecated and its use is no longer recommended. ```yaml Trainer YAML theme={null} trainer: init: model: name: "fc_mnist" mixed_precision: True depth: 10 hidden_size: 50 dropout: 0.0 activation_fn: "relu" optimizer: SGD: lr: 0.1 # Unused since we have a scheduler momentum: 0.9 schedulers: ConstantLR: learning_rate: 0.001 precision: loss_scaling_factor: 1.0 loop: max_steps: 10000 logging: log_steps: 50 checkpoint: steps: 2000 seed: 1 fit: train_dataloader: data_dir: "./data/mnist/train" batch_size: 128 drop_last_batch: True shuffle: True to_float16: True val_dataloader: &id001 data_dir: "./data/mnist/val" batch_size: 128 drop_last_batch: True to_float16: True validate: val_dataloader: *id001 validate_all: val_dataloaders: *id001 ``` ```yaml Trainer Legacy YAML theme={null} train_input: data_dir: "./data/mnist/train" batch_size: 128 drop_last_batch: True shuffle: True to_float16: True eval_input: data_dir: "./data/mnist/val" batch_size: 128 drop_last_batch: True to_float16: True model: name: "fc_mnist" mixed_precision: True depth: 10 hidden_size: 50 dropout: 0.0 activation_fn: "relu" optimizer: optimizer_type: "SGD" learning_rate: 0.001 momentum: 0.9 loss_scaling_factor: 1.0 runconfig: max_steps: 10000 checkpoint_steps: 2000 log_steps: 50 seed: 1 ``` #### Execute Script with Run Function All models in Cerebras Model Zoo use the `run` function inside the script `run.py`. Therefore, once you have ported your model to use the `run` function, you can follow the steps in [Launch your job](../../fundamentals/launch-your-job) section to launch your training or evaluation job. ### Logging and Evaluation Metrics By default, the run function logs training information to the console and to TensorBoard, as explained in [Measure throughput of your model](../../fundamentals/measure-throughput-of-your-model). You can also define your your own scalar and tensor summaries. The Cerebras Model Zoo git repository uses a base class to compute evaluation metrics called `CBMetric`. Metrics already defined in the Model Zoo git repository can be imported as: ```python theme={null} from cerebras.pytorch.metrics import ( AccuracyMetric, DiceCoefficientMetric, MeanIOUMetric, PerplexityMetric, ) ``` As an example, the [GPT2 implementation in PyTorch](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gpt2/model.py) uses some of these metrics. How to use evaluation metrics: 1. **Registration**: All metrics must be registered with the corresponding `torch.nn.Module` class. This is automatically done when the `CBMetric` object is constructed. That is, to register a metric to a `torch.nn.Module` class, construct the metric object in the `torch.nn.Module` class’ constructor. 2. **Update**: The metrics are stateful. This means that every call to the metric object with the appropriate arguments automatically the latest metric value and save it in the metric’s internal state. 3. **Logging**: At the very end of the run, the final metrics values will be computed and then logged both to the console and to the TensorBoard `SummaryWriter`. ## Conclusion Porting PyTorch models to Cerebras systems offers significant advantages in terms of performance, scalability, and efficiency. By leveraging the specialized hardware and extensive resources provided by Cerebras, you can optimize your neural network models for large-scale data processing and complex computations. This guide has outlined the essential steps for successfully porting and adapting PyTorch models to run on Cerebras systems, including: * Setting Up the Cerebras Environment: Ensuring all necessary installations and configurations are in place. * Configuring Data Processing: Preparing and customizing datasets for pre-training and fine-tuning. * Adapting Model Architecture: Modifying existing models or creating new ones to be compatible with Cerebras hardware. * Running Training and Evaluation Scripts: Utilizing the run function and managing parameters for efficient experimentation. By following the pathways and guidelines provided, whether you choose to adapt existing models or develop new ones, you can take full advantage of the capabilities offered by Cerebras systems. Starting with the robust foundation provided by the Cerebras Model Zoo, you can streamline the development process and achieve superior results. # S3 Checkpointing Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/migration/s3-checkpoints Save, load, and manage checkpoints using S3-compatible storage. You can save and load model checkpoints using any S3-compatible storage. This lets you: * Persist training progress remotely * Share checkpoints across environments * Manage checkpoints easily with CLI tools This is ideal for large-scale or distributed training where local storage is limited or ephemeral. ## Setup Before saving checkpoints to S3, you need to configure credentials so your environment can authenticate with your S3-compatible service. You can do this either by using an AWS-style config file or by setting environment variables. Both methods are supported, and you can switch between them based on your setup or deployment environment. ### Option 1: AWS Config File (`~/.aws/config`) Use this method when you want to define multiple named profiles and keep credentials stored locally in a file. ```yaml theme={null} [default] aws_access_key_id = ... aws_secret_access_key = ... endpoint_url = ... [profile truenas] aws_access_key_id = ... aws_secret_access_key = ... aws_endpoint_url = ... ``` To use a specific profile: ```python theme={null} cstorch.backends.csx.storage.s3.profile = "truenas" ``` Or in YAML: ```yaml theme={null} trainer: init: callbacks: - GlobalFlags: csx.storage.s3.profile: truenas ``` > [!NOTE] > > If `csx.storage.s3.profile` is not specified or is set to `None`, the system will default to the `[default]` profile. ### Option 2: Environment Variables If you’re running in containers or ephemeral environments, exporting credentials directly as environment variables may be more convenient. ```bash theme={null} export AWS_CONFIG_FILE=... export AWS_PROFILE=... export AWS_ENDPOINT_URL=... export AWS_ACCESS_KEY_ID=... export AWS_SECRET_ACCESS_KEY=... export AWS_SESSION_TOKEN=... ``` If the system can’t find valid credentials, it will raise an error. > [!NOTE] > > For other methods of configuring [endpoints](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html#using-environment-variables) and credentials, see the [AWS documentation](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html). ## Use the S3 Checkpoint API Once credentials are in place, you can save and load checkpoints simply by using an S3 path. This integration works directly with cstorch.save and cstorch.load, so you don't need to change your workflow — just update the path. ### With Cerebras PyTorch Specify an s3:// path in your calls to save and load model state dictionaries. ```python theme={null} state_dict = {...} cstorch.save(state_dict, "s3://bucket/prefix/checkpoint.mdl") state_dict = cstorch.load("s3://bucket/prefix/checkpoint.mdl") ``` ### Upload Checkpoints to S3 Use the `cszoo checkpoint copy` command to upload checkpoints to S3. ```bash theme={null} cszoo checkpoint copy /path/to/local/checkpoint.mdl s3://bucket/path/to/remote/checkpoint.mdl ``` Your S3 path must: * Start with s3:// * Include the bucket name * Include the object path * If the bucket doesn’t exist and you have permission, the system will create it automatically. * If the bucket exists but your credentials do not have permission to access it, the system will raise a permission error. ### With ModelZoo Trainer You can configure the ModelZoo Trainer to save directly to S3 by setting checkpoint\_root. This makes checkpointing seamless — just point to an S3 path, and the trainer handles the rest. > [!NOTE] > > If you don’t specify `checkpoint_root`, the system saves to the local filesystem by default. ```python theme={null} from cerebras.modelzoo.trainer import Trainer from cerebras.modelzoo.trainer.callbacks import Checkpoint trainer = Trainer( ..., checkpoint=Checkpoint(checkpoint_root="s3://bucket/prefix") ) ``` Or configure it in YAML: ```yaml theme={null} trainer: init: ... checkpoint: checkpoint_root: s3://bucket/prefix ``` This setup will save checkpoints as: ``` s3://bucket/prefix/checkpoint_{step}.mdl ``` ### Load Checkpoints from S3 with ModelZoo Trainer To resume training from a checkpoint stored in S3, just specify the checkpoint path using ckpt\_path. ```yaml theme={null} trainer: ... fit: ckpt_path: s3://bucket/path/to/remote/checkpoint.mdl ... ``` > [!NOTE] > > If your checkpoint contains tensors with a different dtype than expected (e.g., BF16 instead of F32), it may trigger inefficient type casting that slows down performance—this issue does not affect checkpoints saved during a Cerebras training run. # Intro to Model Zoo Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/model-zoo-overview Get an overview of the Cerebras Model Zoo, including model portability, modules, and updated directory paths for enhanced usability. The [Cerebras Model Zoo](https://github.com/Cerebras/modelzoo) is a comprehensive repository offering a range of deep learning models optimized for the Cerebras hardware. This collection is tailored to showcase the best practices for constructing models that exploit the robust capabilities of the Cerebras Wafer-Scale Cluster. With a focus on models developed in PyTorch, the Model Zoo provides detailed instructions for deploying neural network jobs on the Cerebras hardware, guiding users through compiling, validating, and training processes. > [!NOTE] > > From version 2.2 onwards, the Model Zoo has been reorganized to enhance clarity and usability. If you've upgraded from any version prior to 2.2, see [Directory Path Updates](#directory-path-updates) for more info. ## Included Models The [Cerebras Model Zoo](https://github.com/Cerebras/modelzoo) includes various models: | | | | - | - | | [BERT](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/bert/) | [BERT Classifier](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/bert/classifier/) | | [BERT Named Entity Recognition](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/bert/token_classifier/) | [BERT Summarization](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/bert/extractive_summarization/) | | [Bloom](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/bloom/) | [BTLM](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/btlm/) | | [DiT](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/vision/dit/) | [DPO](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/dpo/) | | [DPR](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/dpr/) | [ESM-2](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/esm2/) | | [ESM-2 Classification](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/esm2/classification/) | [Falcon](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/falcon/) | | [GPT-2](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/gpt2/) | [GPT-3](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/gpt3/) | | [GPT-J](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/gptj/) | [GPT-J(Fine-tuning) Summarization](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/gptj/continuous_pretraining) | | [JAIS](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/jais/) | [LLaMA, LLaMA-2, LLaMA-3](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/llama/) | | [Multimodal LLaVA](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/multimodal/llava/) | [Multimodal Simple](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/multimodal/multimodal_simple/) | | [Mistral](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/mistral/) | [Mixtral](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/mixtral/) | | [Starcoder](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/starcoder/) | [RoBERTa](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/bert/) | | [Transformer](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/transformer/) | [T5](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/t5/) | To deploy your neural network jobs on the Cerebras Wafer-Scale Cluster, refer to the Quick start guide. This guide will walk you through the necessary steps to compile, validate, and train models from this Model Zoo using your preferred framework. ## Model Portability The [Cerebras Model Zoo](https://github.com/Cerebras/modelzoo) facilitates model portability, providing tools that aid users in adapting existing models or crafting new ones using Cerebras APIs. This includes a spectrum of user stages, from beginners to advanced users, with varying levels of integration and customization: ### Beginners Start with Cerebras [data preprocessing tools](../model-zoo/components/dataloaders/dataloaders-for-pytorch) and use model implementations found in the [Cerebras Model Zoo](https://github.com/Cerebras/modelzoo). ### Intermediate Users Intermediate users can integrate their data preprocessing methods by referring to the section [Create your own data preprocessing](../model-zoo/components/data-preprocessing/data-preprocessing). ### Advanced Users Define your PyTorch model or code using the `run` function in the [Cerebras Model Zoo](https://github.com/Cerebras/modelzoo) and [Supported Operations API](../model-zoo/api). ## Structure The Model Zoo is designed to be user-friendly, offering an organized array of models, datasets, tools, and utilities. Key features include: * Reorganized models and datasets categorized by classes (**NLP**, **Vision**, **Multimodal**). * Registry APIs that enable querying of paths and supported combinations for each model. * Config classes designed to encapsulate parameters in YAML files, providing a clear class hierarchy and ensuring the validation of configurations used with models. * Enhanced data preprocessing tools for NLP models, significantly improving performance. The structure of the Cerebras Model Zoo is illustrated in the diagram below: ![](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/model-zoo/model_reorg.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=ef59feb8ff48051e2db0604327135a7c) Fig. 7 Cerebras Model Zoo structure ### Modules The principal modules in the Cerebras Model Zoo include: | Modules | Description | | - | - | | [modelzoo.config](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/config) | For configuration classes and base-level configuration. | | [modelzoo.data](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/data/) | Hosting data processing scripts and loaders for vision and NLP models | | [modelzoo.layers](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/layers/) | Containing layers and modules for model building and adaptation | | [modelzoo.losses](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/losses/) | Offering a variety of loss functions for different model training phases | | [modelzoo.models](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/) | Implementing a range of models across NLP, vision, and multimodal domains | | [modelzoo.data\_preparation](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/data_preparation/) | Providing tools for data preprocessing stages | | [modelzoo.tools](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/tools/) | Containing utilities for model conversion and configuration | | [modelzoo.common](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/common/) | Hosting common utilities across different models | | [modelzoo.trainer](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/trainer/) | Trainer API that facilitates training and validating Model Zoo models | This redesign aims to streamline the user experience, making it easier for ML developers and researchers to explore, experiment, and develop solutions efficiently within the Cerebras ecosystem. The documentation further enriches this experience, offering examples and guidance on utilizing the Model Zoo’s Registry APIs and Config Classes, thereby enhancing the model development and deployment process. ## Directory Path Updates If you're updating to the latest version of Model Zoo from any version **prior to 2.2**, the paths have been updated. See the table to compare the old paths with their corresponding new versions. | Old Path (relative to \$MODELZOO) | New Path (relative to \$MODELZOO) | | - | - | | common/pytorch/\* common/run\_utils/\* common/model\_utils/\* | common/ | | common/pytorch/layers | layers/ | | common/pytorch/input common/input | data/ | | models/nlp/\* vision/pytorch/\* multimodal/pytorch/\* | models/nlp/\* models/vision/\* models/multimodal/\* | | data\_preparation/\* | data\_preparation/ | | common/pytorch/model\_utils/ | tools/ | | fc\_mnist/ | fc\_mnist/ | # LLaVA Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/multimodal/llava Multimodal model that connects a vision encoder to a language model through instruction tuning on GPT-4-generated image-text data. ## Model Description LLaVA (Large Language and Vision Assistant) is a multimodal model that integrates a vision encoder with a language model via a lightweight projector module, enabling end-to-end visual and language understanding. It accepts both image and text inputs and generates text-based outputs, making it suitable for instruction-following, question answering, and general-purpose visual dialogue tasks. The architecture consists of three components: * A **vision encoder** initialized from pretrained OpenAI CLIP-ViT-L/14-336px. * A **language model** initialized from Vicuna weights. * A **projector module**, implemented as a multi-layer perceptron (MLP), which maps image embeddings into the language model’s token embedding space. Training occurs in two distinct phases: 1. **Feature Alignment Pretraining**: Only the projector module is trained in this phase. Its weights are updated to align the image features from the vision encoder with the word embeddings of the language model. 2. **Instruction Finetuning**:The model is trained on instruction-following data to enable chatbot capabilities. During this phase, the language model and projector are typically finetuned, while the vision encoder remains frozen. ## Code Structure The code for this model is located in the [`llava`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/multimodal/llava) directory within the ModelZoo. Here’s how it's organized: * [`configs/`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/multimodal/llava/configs): Contains YAML configuration files used for training, evaluation, and instruction fine-tuning. * [`model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/multimodal/llava/model.py): Defines the top-level LLaVA model class, encapsulating the vision encoder, projector, and language model modules, and orchestrating forward passes for training and inference. * [`modeling_llava.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/multimodal/llava/modeling_llava.py): Implements core building blocks including the projector MLP, model loading utilities, and integration logic to bridge image features into the LLM token embedding space. ## Available Configurations | Configuration | Description | | :- | :- | | [`params_llava_v1p5_pretrain_13b_phase1_MSL2K.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/multimodal/llava/configs/params_llava_v1p5_pretrain_13b_phase1_MSL2K.yaml) | Phase 1: Feature alignment pretraining for 13B model (MSL=2048). | | [`params_llava_v1p5_pretrain_13b_phase2_MSL2K.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/multimodal/llava/configs/params_llava_v1p5_pretrain_13b_phase2_MSL2K.yaml) | Phase 2: Instruction fine-tuning for 13B model (MSL=2048). | | [`params_llava_v1p5_pretrain_7b_phase1_MSL2K.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/multimodal/llava/configs/params_llava_v1p5_pretrain_7b_phase1_MSL2K.yaml) | Phase 1: Feature alignment pretraining for 7B model (MSL=2048). | | [`params_llava_v1p5_pretrain_7b_phase2_MSL2K.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/multimodal/llava/configs/params_llava_v1p5_pretrain_7b_phase2_MSL2K.yaml) | Phase 2: Instruction fine-tuning for 7B model (MSL=2048). | ## Dataset Download and Preprocessing Please follow the instructions [here](https://huggingface.co/docs/hub/en/datasets-downloading#using-git) for datasets to be downloaded from HuggingFace Datasets. Since all datasets on the HuggingFace Hub are Git repositories, the datasets can be downloaded locally by running `git clone`: ``` git lfs install git clone git@hf.co:datasets/ ``` We provide script [`preprocess_dataset.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/data_preparation/multimodal/llava/preprocess_dataset.py) to further pre-process some of the Phase-1 and Phase-2 datasets into the correct LLaVA jsonl formats. Please see the help message to see which datasets are covered and find more details in the below sections regarding each individual datasets. Additionally, we provide an additional utility option `convert_json2jsonl` to convert a folder of json files to jsonl files - the latter will be the input format that the later [HDF5 processing scripts](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/data_preparation/nlp/hdf5_preprocessing) will act on. ``` python preprocess_dataset.py -h usage: Pre-process LLaVa datasets [-h] {ai2d,arxivcap,arxivqa,chartqa,sp_docvqa,infographics_docvqa,dvqa,synthdog_en,convert_json2jsonl} ... positional arguments: {ai2d,arxivcap,arxivqa,chartqa,sp_docvqa,infographics_docvqa,dvqa,synthdog_en,convert_json2jsonl} ai2d Pre-process AI2D dataset arxivcap Pre-process ArxivCAP dataset arxivqa Pre-process ArxivQA dataset chartqa Pre-process ChartQA dataset sp_docvqa Pre-process SP-DocVQA dataset infographics_docvqa Pre-process Infographics-DocVQA dataset dvqa Pre-process DVQA dataset synthdog_en Pre-process Synthdog_EN dataset convert_json2jsonl Pre-process json files to jsonl files optional arguments: -h, --help show this help message and exit ``` Note: **We currently expect all the images under a single parent folder and the relative path of images from different datasets are written under `image_key` in the H5 files generated.** For example: ``` train_input.img_data_dir ├── coco ├── gqa ├── ocr_vqa ├── textvqa └── vg ``` ### Phase-1: Pre-training for Feature alignment datasets: #### LLaVA Visual Instruct Pretrain LCS-558K Dataset * Download from [https://huggingface.co/datasets/liuhaotian/LLaVA-Pretrain](https://huggingface.co/datasets/liuhaotian/LLaVA-Pretrain) * Dataset and images can be directly downloaded from HuggingFace Hub Datasets using\ `git clone git@hf.co:datasets/liuhaotian/LLaVA-Pretrain` * *No further preprocessing is required* #### ShareGPT4V-PT Dataset * Download the dataset `share-captioner_coco_lcs_sam_1246k_1107.json` from HuggingFace [here](https://huggingface.co/datasets/Lin-Chen/ShareGPT4V/tree/main). * This dataset consists of 100K high-quality captions collected from advanced GPT4-Vision and has been expanded to 1.2 million with a caption model trained on this subset. * Images for this dataset can be downloaded by following the instructions [here](https://github.com/InternLM/InternLM-XComposer/blob/main/projects/ShareGPT4V/docs/Data.md#prepare-images) * *No further preprocessing is required* #### Synthdog-EN Dataset * Download the dataset from HuggingFace: [https://huggingface.co/datasets/naver-clova-ix/synthdog-en](https://huggingface.co/datasets/naver-clova-ix/synthdog-en) * The images for this dataset are present in the parquet files * Steps for preprocessing dataset: * Place the downloaded files at `//synthdog-en` * Use [`preprocess_dataset.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/data_preparation/multimodal/llava/preprocess_dataset.py) to process the data into LLaVa jsonl format. Please see the required input arguments. ``` python preprocess_dataset.py synthdog_en -h usage: Pre-process LLaVa datasets synthdog_en [-h] --input_dir INPUT_DIR --output_jsonl_dir OUTPUT_JSONL_DIR --output_parquet_dir OUTPUT_PARQUET_DIR --parquet_range PARQUET_RANGE [PARQUET_RANGE ...] --output_image_dir OUTPUT_IMAGE_DIR --image_prefix IMAGE_PREFIX optional arguments: -h, --help show this help message and exit --input_dir INPUT_DIR Input directory of Synthdog-EN dataset parquet files. --output_jsonl_dir OUTPUT_JSONL_DIR Output directory of Synthdog-EN processed json files with LLaVa jsonl format. --output_parquet_dir OUTPUT_PARQUET_DIR Output directory of Synthdog-EN processed parquet files. --parquet_range PARQUET_RANGE [PARQUET_RANGE ...] Range of Synthdog-EN parquet files to be selected. --output_image_dir OUTPUT_IMAGE_DIR Directory of Synthdog-EN image files. --image_prefix IMAGE_PREFIX Relative path prefix for Synthdog-EN image files. ``` * Example command: ``` python preprocess_dataset.py synthdog_en \ --input_dir=//synthdog-en/data \ --output_jsonl_dir=//synthdog-en/llava_processed_jsons \ --output_parquet_dir=//synthdog-en/llava_processed_parquet \ --parquet_range 3 11 \ --output_image_dir=//synthdog-en/images \ --image_prefix=synthdog-en/images ``` ### Phase-2: Instruction Finetuning datasets #### LLaVA Visual Instruct 150K Dataset * Download the dataset `llava_v1_5_mix665k.json` from [https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava\_v1\_5\_mix665k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava_v1_5_mix665k.json) * Images corresponding to this dataset can be downloaded by following instructions [here](https://github.com/haotian-liu/LLaVA/blob/main/README.md#visual-instruction-tuning) * *No further preprocessing is required* #### ShareGPT4V-SFT Dataset: * Download the dataset `sharegpt4v_mix665k_cap23k_coco-ap9k_lcs3k_sam9k_div2k.json` from HuggingFace [here](https://huggingface.co/datasets/Lin-Chen/ShareGPT4V/tree/main). * This dataset is built by replacing 23K image-text pairs related to the image captioning task in LLaVA-mix-665K with a equivalent subset in collected GPT4V-generated high-quality image-text pairs. * Images for this dataset can be downloaded by following the instructions [here](https://github.com/InternLM/InternLM-XComposer/blob/main/projects/ShareGPT4V/docs/Data.md#prepare-images) * *No further preprocessing is required* #### ChartQA Dataset * Download the dataset from HuggingFaceHub Datasets from the link: [https://huggingface.co/datasets/ahmed-masry/ChartQA](https://huggingface.co/datasets/ahmed-masry/ChartQA) * Steps for preprocessing dataset: * Place the downloaded files at `//ChartQA_Dataset` * Use [`preprocess_dataset.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/data_preparation/multimodal/llava/preprocess_dataset.py) to process the data into LLaVa jsonl format. Please see the required input arguments: ``` python preprocess_dataset.py chartqa -h usage: Pre-process LLaVa datasets chartqa [-h] --dataset_folder DATASET_FOLDER optional arguments: -h, --help show this help message and exit --dataset_folder DATASET_FOLDER Path to the ChartQA dataset folder with the data split folders. ``` * Example command: ``` python preprocess_dataset.py chartqa --dataset_folder //ChartQA_Dataset ``` #### DVQA Dataset * The dataset can be downloaded by following instructions mentioned in [https://github.com/kushalkafle/DVQA\_dataset?tab=readme-ov-file#download-links](https://github.com/kushalkafle/DVQA_dataset?tab=readme-ov-file#download-links) * Steps for preprocessing dataset: * Place the downloaded files at `//DVQA` * Use [`preprocess_dataset.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/data_preparation/multimodal/llava/preprocess_dataset.py) to process the data into LLaVa jsonl format. Please see the required input arguments: ``` python preprocess_dataset.py dvqa -h usage: Pre-process LLaVa datasets dvqa [-h] --dataset_folder DATASET_FOLDER optional arguments: -h, --help show this help message and exit --dataset_folder DATASET_FOLDER Path to the DVQA dataset folder with the data files. ``` * Example command: ``` python preprocess_dataset.py dvqa --dataset_folder //DVQA/qa ``` #### AI2 Diagram Dataset * Download the dataset and images using ``` wget https://ai2-public-datasets.s3.amazonaws.com/diagrams/ai2d-all.zip ``` * Steps for preprocessing dataset: * Unzip the downloaded zip file to `//ai2d` * Use [`preprocess_dataset.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/data_preparation/multimodal/llava/preprocess_dataset.py) to process the data into LLaVa jsonl format. Please see the required input arguments: ``` python preprocess_dataset.py ai2d -h usage: Pre-process LLaVa datasets ai2d [-h] --question_dir QUESTION_DIR --output_jsonl_dir OUTPUT_JSONL_DIR optional arguments: -h, --help show this help message and exit --question_dir QUESTION_DIR Path to the AI2D question directory, which contains json files describing the question and answer corresponding to an image. --output_jsonl_dir OUTPUT_JSONL_DIR Folder to write the AI2D output jsonl files, which is in LLaVa format describing the image and associated question and answer. ``` * Example command: ``` python preprocess_dataset.py ai2d --question_dir //ai2d/questions --output_jsonl_dir //ai2d/ai2d_llava_jsonl ``` #### ArxivQA Dataset * The dataset can be downloaded from [https://huggingface.co/datasets/MMInstruction/ArxivQA](https://huggingface.co/datasets/MMInstruction/ArxivQA) * Steps for preprocessing dataset: * Place the downloaded files at `//ArxivQA` * Use [`preprocess_dataset.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/data_preparation/multimodal/llava/preprocess_dataset.py) to process the data into LLaVa jsonl format. Please see the required input arguments: ``` python preprocess_dataset.py arxivqa -h usage: Pre-process LLaVa datasets arxivqa [-h] --input_file INPUT_FILE --output_jsonl_dir OUTPUT_JSONL_DIR optional arguments: -h, --help show this help message and exit --input_file INPUT_FILE Path to the ArxivQA question file, which contains the question and answer corresponding to an image. --output_jsonl_dir OUTPUT_JSONL_DIR Folder to write the ArxivQA output jsonl files, which is in LLaVa format describing the image and associated question and answer. ``` * Example command: ``` python preprocess_dataset.py arxivqa --input_file //ArxivQA/arxivqa.jsonl --output_jsonl_dir //ArxivQA/arxivqa_llava_jsonl ``` #### ArxivCap Dataset * The dataset can be downloaded from [https://huggingface.co/datasets/MMInstruction/ArxivCap](https://huggingface.co/datasets/MMInstruction/ArxivCap). * We process and use only figures with captions. Any subfigures are not included. * Steps for preprocessing dataset: * Place the downloaded files at `//ArxivCAP` * Use [`preprocess_dataset.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/data_preparation/multimodal/llava/preprocess_dataset.py) to process the data into LLaVa jsonl format. Please see the required input arguments: ``` python preprocess_dataset.py arxivqa -h usage: Pre-process LLaVa datasets arxivqa [-h] --input_file INPUT_FILE --output_jsonl_dir OUTPUT_JSONL_DIR optional arguments: -h, --help show this help message and exit --input_file INPUT_FILE Path to the ArxivQA question file, which contains the question and answer corresponding to an image. --output_jsonl_dir OUTPUT_JSONL_DIR Folder to write the ArxivQA output jsonl files, which is in LLaVa format describing the image and associated question and answer. ``` * Example command: ``` python preprocess_dataset.py arxivcap \ --input_dir=//ArxivCap/data \ --output_jsonl_dir=//ArxivCap/llava_processed_jsons \ --output_parquet_dir=//ArxivCap/llava_processed_parquet \ --parquet_range 3 11 \ --output_image_dir=//ArxivCap/images \ --image_prefix=ArxivCap/images ``` #### DocVQA Dataset * Download the dataset following instructions [here](https://www.docvqa.org/datasets/docvqa) * Registration is required to download the dataset under `Single Document Visual Question Answering` * Steps for preprocessing dataset: * Place the downloaded files at `//DocVQA` * Use [`preprocess_dataset.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/data_preparation/multimodal/llava/preprocess_dataset.py) to process each subset into LLaVa jsonl format. Please see the required input arguments: ``` python preprocess_dataset.py sp_docvqa -h usage: Pre-process LLaVa datasets sp_docvqa [-h] --dataset_folder DATASET_FOLDER optional arguments: -h, --help show this help message and exit --dataset_folder DATASET_FOLDER Path to the SP-DocVQA dataset folder with the data files. python preprocess_dataset.py infographics_docvqa -h usage: Pre-process LLaVa datasets infographics_docvqa [-h] --dataset_folder DATASET_FOLDER optional arguments: -h, --help show this help message and exit --dataset_folder DATASET_FOLDER Path to the Inforgraphics-DocVQA dataset folder with the data files. ``` * Example commands: ``` python preprocess_dataset.py sp_docvqa --dataset_folder //DocVQA/SP-DocVQA/qa python preprocess_dataset.py infographics_docvqa --dataset_folder //DocVQA/Infographicsvqa/qa ``` ## Sequence of the steps to perform The high-level steps for training a model are relatively simple, involving data-processing and then model training and evaluation * Step 1: Dataset download and preprocessing * Step 2: Generate H5 files for training * Generate files for Phase-1 (Pre-training for Feature alignment) stage * Generate files for Phase-2 (Instruction Finetuning) stage * Step 3: Download pretrained checkpoints for Phase 1 * Step 4: Convert checkpoints to CS Model Zoo format using checkpoint converter * Step 5: Training the model on CS system or GPU using `run.py` * To compile/validate, run train and eval on Cerebras System * To run train and eval on GPU/CPU * Phase-1 training * Phase-2 training * Step 6: Convert checkpoint to source code repository format to run eval * Step 7: Set up source code repository for benchmark evaluation and run evaluation. The steps are elaborated below: ### Step 1: Dataset download and preparation Please follow instructions in Dataset download and preprocessing to setup datasets for the appropriate phase for H5 file generation ### Step 2: Generate H5 files for training The next step is to generate H5 files that are used by the model during training using [LlavaHDF5MapDataProcessor](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/data/multimodal/llava/LlavaHDF5MapDataProcessor.py). We use [`create_hdf5_dataset.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/data_preparation/nlp/hdf5_preprocessing/) to create preprocessed dataset files. Further details on usage and instructions can be found [here](../../components/data-preprocessing/data-preprocessing). #### Generate files for Phase-1 (Pre-training for Feature alignment) stage Refer to LlavaPhaseOnePreprocessor and config file for Phase-1 H5 file generation: [llava\_phase\_1\_preproc.yaml](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/data_preparation/nlp/hdf5_preprocessing/configs/llava_phase_1_preproc.yaml). Please update the following fields in `llava_phase_1_preproc.yaml` appropriately: 1. `setup.input_dir`: Input data directory containing jsonl files. 2. `setup.output_dir`: Output directory to save generated H5 files 3. `setup.processes`: Adjust based on cores available for parallel processing 4. `processor.tokenizer_type`: Tokenizer to use 5. `processor.max_sequence_length`: Maximum sequence length that the model is trained on. This includes the token positions to be used for image data features as well. This means that the number of tokens available for text tokens is `processor.max_sequence_length - dataset.num_patches - 1(BOS token)` 6. `dataset.num_patches`: Number of patches obtained after the image is patchified. This is computed based on the following: 7. `dataset.image_dir`: Parent directory where all the images are present. Used along with the relative path under the `image_key` field in jsonl to check that images exist, and throw out examples with no image. **Command to generate H5 files for Phase 1 and shuffle** ``` cd modelzoo/data_preparation/nlp/hdf5_preprocessing python create_hdf5_dataset.py LlavaPhaseOne --params configs/llava_phase_1_preproc.yaml ``` **Shuffle samples across H5 files** ``` cd modelzoo/data_preparation/hdf5_shuffling bash launch_h5_shuffle.sh --multi_modal ``` More information about shuffling script can be found [here](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/data_preparation/hdf5_shuffling/README.md) #### Generate files for Phase-2 (Instruction Finetuning) stage Refer to LlavaPhaseTwoPreprocessor and config file for Phase-2 H5 file generation: [llava\_phase\_2\_preproc.yaml](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/data_preparation/nlp/hdf5_preprocessing/configs/llava_phase_2_preproc.yaml). The fields to be updated include * All fields mentioned for Phase-1 [above](#generate-files-for-phase-1-pre-training-for-feature-alignment-stage) * Please note the field `dataset.system_prompt_style`: `vicuna_v1`. This is used to transform the instruction finetuning dataset into the `vicuna_v1` format with appropriate system message and `USER` and `ASSISTANT` values. Note that we currently support `vicuna_v1` only. * Support for other formats such as `llama`, `zephyr` is planned for future releases. **Command to generate H5 files for Phase 2** ``` cd modelzoo/data_preparation/nlp/hdf5_preprocessing python create_hdf5_dataset.py LlavaPhaseTwo --params configs/llava_phase_2_preproc.yaml ``` **Shuffle samples across H5 files** ``` cd modelzoo/data_preparation/hdf5_shuffling bash launch_h5_shuffle.sh --multi_modal ``` More information about shuffling script can be found [here](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/data_preparation/hdf5_shuffling/README.md) ### Step 3: Download pretrained checkpoints for Phase-1 Checkpoint converter script for converting CLIP-ViT and Vicuna checkpoints to CS format require the following directory structure: ``` /path/to/pretrained/checkpoints ├── image_model │   ├── config.json │   ├── preprocessor_config.json │   └── pytorch_model.bin └── text_model ├── config.json ├── config_lmsys.json ├── pytorch_model-00001-of-00002.bin ├── pytorch_model-00002-of-00002.bin ├── pytorch_model.bin.index.json ├── tokenizer_config.json ├── special_tokens_map.json └── tokenizer.model ``` a. [openai/clip-vit-large-patch14-336](https://huggingface.co/openai/clip-vit-large-patch14-336/tree/main) checkpoints, config.json and preprocessor\_config.json should be downloaded to a subdirectory `image_model`. ``` cd /path/to/pretrained/checkpoints git lfs install git clone https://huggingface.co/openai/clip-vit-large-patch14-336 image_model ``` b. [lmsys/vicuna-7b-v1.5](https://huggingface.co/lmsys/vicuna-7b-v1.5/tree/main) checkpoints and tokenizer files should be downloaded to a subdirectory `text_model` ``` cd /path/to/pretrained/checkpoints git lfs install git clone https://huggingface.co/lmsys/vicuna-7b-v1.5 text_model ``` c. Rename `config.json` to `config_lmsys.json` ``` mv /path/to/pretrained/checkpoints/text_model/config.json /path/to/pretrained/checkpoints/text_model/config_lmsys.json ``` d. Download [LLaVA-7B config.json](https://huggingface.co/liuhaotian/llava-v1.5-7b/blob/main/config.json) from HuggingFace ``` cd /path/to/pretrained/checkpoints/text_model wget https://huggingface.co/liuhaotian/llava-v1.5-7b/raw/main/config.json ``` We do steps (c) and (d) above since we need additional information about LLaVA model such as `mm_projector_type` etc to build appropriate CS config yaml and checkpoint **Note: In case of LLaVA-13B** * The image model remains the same, so you follow the same step (a) as above and download from [openai/clip-vit-large-patch14-336](https://huggingface.co/openai/clip-vit-large-patch14-336/tree/main). * Download `text_model` from [lmsys/vicuna-13b-v1.5](https://huggingface.co/lmsys/vicuna-13b-v1.5/tree/main) in step (b) * Rename `config.json` to `config_lmsys.json`, same as step (c) * Download [LLaVA-13B config.json](https://huggingface.co/liuhaotian/llava-v1.5-13b/blob/main/config.json) in step (d) ### Step 4: Convert checkpoints to CS Model Zoo format using checkpoint converter * Checkpoint conversion script: [modelzoo/tools/convert\_checkpoint.py](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/tools/convert_checkpoint.py) * LLaVA Model checkpoint converter: [modelzoo/tools/checkpoint\_converters/llava.py](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/tools/checkpoint_converters/llava.py) * Command: ``` python modelzoo/tools/convert_checkpoint.py convert \ --model llava \ --src-fmt hf \ --tgt-fmt cs-2.2 \ --output-dir /path/to/converted_checkpoint \ --config /path/to/pretrained/checkpoints \ /path/to/pretrained/checkpoints ``` More information about checkpoint converters can be obtained by `python modelzoo/tools/convert_checkpoint.py list` ### Step 5: Training the model on CS system or GPU using `run.py` **IMPORTANT**: See the following notes before proceeding further. **Parameter settings in YAML config file**: The config YAML files are located in the [configs](configs/) directory. Before starting a training run, make sure that the YAML configs used have the following set correctly: * The `train_input.data_dir` parameter points to the correct dataset * The `train_input.img_data_dir` parameter points to the correct parent directory containing all images needed by the dataset. * The `train_input.image_size` parameter corresponds to the image-size of the dataset. * Also change sizes in `train_input.transforms` appropriately if `train_input.image_size` is updated. * The `model.image_model.image_size` points to the image size passed to ViTModel * The `model.image_model.patch_size` parameter to use different patch sizes * `model.freeze` contains the regex patterns to freeze appropriate layers in the model * `model.image_feature_select_layer_idx` parameter to specify the image\_model encoder layer from which features are extracted for the input image. * `model.image_start_idx` parameter: This parameter should be set based on the `data_params.json` file that is saved when H5 files are generated using `create_hdf5_dataset.py`. In general, * Phase-1: `model.image_start_idx: 1` * Phase-2 with `dataset.system_prompt_style: vicuna_v1`: `model.image_start_idx: 35` **YAML config files**: Details on the configs for this model can be found in the configs included for this model In the following example run commands, we use `/path/to/yaml`, `/path/to/model_dir`, and `train` as placeholders for user supplied inputs. * `/path/to/yaml` is a path to the YAML config file with model parameters such one of the configurations described in the configs included for this model. * `/path/to/model_dir` is a path to the directory where we would like to store the logs and other artifacts of the run. * `--mode` specifies the desired mode to run the model in. Change to `--mode eval` to run in eval mode. #### To run train and eval on GPU/CPU If running on a CPU or GPU, activate the environment from [Python GPU Environment setup](https://github.com/Cerebras/modelzoo/blob/main/PYTHON-SETUP.md), and simply run: ``` python run.py {CPU,GPU} \ --mode train \ --params /path/to/yaml \ --model_dir /path/to/model_dir ``` In case of LLaVA, training is a two stage process as below: * **Phase-1 (Pre-training for Feature alignment) stage** * To launch this phase, we initialize the model using converted checkpoint from Step-4 * **Command**: ``` python run.py {CPU,GPU} \ --mode train \ --params /path/to/phase-1-llava-yaml \ --model_dir /path/to/model_dir_phase_1 \ --checkpoint_path /path/to/Step4/converted_checkpoint_mdl_file ``` * **Phase-2 (Instruction Finetuning) stage** * When instruction finetuning, the model is **initialized** from the **checkpoint from Phase-1**. * **Command**: ``` python run.py {CPU,GPU} \ --mode train \ --params /path/to/phase-2-llava-yaml \ --model_dir /path/to/model_dir \ --checkpoint_path /path/to/model_dir_phase_1/checkpoint_.mdl ``` * **Note: The yaml from Phase-2 should only load model states from Phase-1 checkpoint by setting the yaml flag `runconfig.load_checkpoint_states: "model"`** ### Step 6: Convert checkpoint to source code repository format to run eval We perform evaluations on multimodal benchmarks using LLaVA source code repository. For this, we need to convert the checkpoints generated using the training run from Phase-2 to LLaVA source code repository format. This can be done using the command: ``` python modelzoo/tools/convert_checkpoint.py convert \ --model llava \ --src-fmt cs-2.2 \ --tgt-fmt hf \ --output-dir /path/to/hf_converted_checkpoint \ --config /path/to/cs_config.yaml \ /path/to/checkpoint_from_phase-2.mdl ``` The above command generates two folders `image_model` and `text_model` under `output-dir` as shown below: ``` /path/to/converted_checkpoint ├── image_model │   ├── config.json │   ├── preprocessor_config.json │   ├── pytorch_model-00001-of-00001.bin │   └── pytorch_model.bin.index.json └── text_model ├── config.json ├── pytorch_model-00001-of-00004.bin ├── pytorch_model-00002-of-00004.bin ├── pytorch_model-00003-of-00004.bin ├── pytorch_model-00004-of-00004.bin ├── pytorch_model.bin.index.json ``` * Folder `image_model` consists of weights for `vision_tower` in source repository * Folder `text_model` consists of weights to be loaded for the Language model and projectors * The LLaVA source code repository expects tokenizer files to be present along with the language model weights ([code pointer](https://github.com/haotian-liu/LLaVA/blob/main/llava/model/builder.py#L116)). For this, **please copy the tokenizer files into `text_model` folder**. * Also, please make sure `text_model.mm_vision_tower` points to the `image_model` path to ensure the weights from `image_model` folder are loaded into the source code `vision_tower`. This path is automatically added during checkpoint conversion. * **Rename folder `text_model` to `text_model_llava`. This is since the source code repository expects the path to include `llava` keyword in order to correctly load the checkpoints. (code pointers: [builder.py](https://github.com/haotian-liu/LLaVA/blob/main/llava/model/builder.py#L48), [mm\_utils.py](https://github.com/haotian-liu/LLaVA/blob/main/llava/mm_utils.py#L207))** * So, after the relevant tokenizer files are copied, the `output-dir` should look like below: ``` /path/to/converted_checkpoint ├── image_model │   ├── config.json │   ├── preprocessor_config.json │   ├── pytorch_model-00001-of-00001.bin │   └── pytorch_model.bin.index.json └── text_model_llava ├── config.json ├── pytorch_model-00001-of-00004.bin ├── pytorch_model-00002-of-00004.bin ├── pytorch_model-00003-of-00004.bin ├── pytorch_model-00004-of-00004.bin ├── pytorch_model.bin.index.json ├── special_tokens_map.json ├── tokenizer_config.json └── tokenizer.model ``` ### Step 7: Set up source code repository for benchmark evaluation and run evaluation benchmarks * Setup LLaVA source code repository for multimodal benchmark evaluation by following instructions mentioned in [Evaluation Docs](https://github.com/haotian-liu/LLaVA/blob/main/docs/Evaluation.md). * Instructions for creating conda environment and setting up the repository are mentioned in [Installation Section](https://github.com/haotian-liu/LLaVA/blob/main/README.md#install) * Scripts to run various benchmarks are provided [here](https://github.com/haotian-liu/LLaVA/tree/main/scripts/v1_5/eval) * **Pass `text_model_llava` folder path to `--model-path` in [eval scripts in LLaVA source code repository](https://github.com/haotian-liu/LLaVA/blob/main/scripts/v1_5/eval/llavabench.sh#L4)** ## DataLoader Features Dictionary [LlavaHDF5MapDataProcessor](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/data/multimodal/llava/LlavaHDF5MapDataProcessor.py) outputs the following features dictionary with keys/values: * `image_data`: Image tensor * Shape: `(batch_size, model.num_channels, model.image_model.image_size[0], model.image_model.image_size[1])` * Type: `torch.float16` * `labels`: Text input tokens to be predicted by model * Shape: `(batch_size, model.text_model.max_sequence_length)` * Type: `torch.int32` * `key_padding_mask`: Mask indicating the positions of image\_tokens. Used in conjunction with causal attention mask(generated on the fly). * Shape: `(batch_size, model.text_model.max_sequence_length)` * Type: `torch.int32` * `1` at positions where we DO NOT want to ATTEND, `0` otherwise * `text_input_ids`: Tensor indicating input text tokens. These include `` token inserted in `[model.image_start_idx: model.image_start_idx+num_patches]` positions * Shape: `(batch_size, model.text_model.max_sequence_length)` * Type: `torch.int32` * `loss_mask`: Mask indicating positions to consider when computing loss. * Shape: `(batch_size, model.text_model.max_sequence_length)` * Type: `torch.int32` * `1` at positions where we want to compute loss, `0` otherwise ## Implementation notes The following modifications and assumptions are made in this implementation: 1. Phase-2 instruction finetuning data includes samples which contain text-only data. For these cases, we pass a dummy image and make sure we do not attend to these dummy image features using `src_key_padding_mask` from the dataloader. 2. Our preprocessing scripts and model defintions all assume that that image occurs at a fixed location with the context length. This is specified in the model definition using `model.image_start_idx` parameter in the yaml 3. We currently support datasets which contain single image per sample. 4. We currently do not support interleaving of multiple images with text. 5. **We currently expect all the images under a single parent folder and the relative path of images from different datasets are written under `image_key` in the H5 files generated.** For example: ``` train_input.img_data_dir ├── coco ├── gqa ├── ocr_vqa ├── textvqa └── vg ``` ## References * [LLaVA-v1: Visual Instruction Tuning](https://arxiv.org/pdf/2304.08485.pdf) * [LLaVA-v1.5: Improved Baselines with Visual Instruction Tuning](https://arxiv.org/pdf/2310.03744.pdf) * [LLaVA source code repository](https://github.com/haotian-liu/LLaVA/tree/main/) * [ShareGPT4V: Improving Large Multi-Modal Models with Better Captions](https://arxiv.org/pdf/2311.12793.pdf) * [SynthDog-EN: OCR-Free Document Understanding Transformer](https://arxiv.org/pdf/2111.15664.pdf) * [ChartQA: A Benchmark for Question Answering about Charts with Visual and Logical Reasoning](https://aclanthology.org/2022.findings-acl.177/) * [DVQA: Understanding Data Visualizations via Question Answering](https://arxiv.org/pdf/1801.08163.pdf) * [AI2D: A Diagram Is Worth A Dozen Images](https://ai2-website.s3.amazonaws.com/publications/Diagrams_ECCV2016.pdf) * [ArxivQA & ArxivCap: Multimodal ArXiv: A Dataset for Improving Scientific Comprehension of Large Vision-Language Models](https://arxiv.org/pdf/2403.00231.pdf) * [DocVQA: A Dataset for VQA on Document Images](https://arxiv.org/pdf/2007.00398.pdf) # Multimodal Simple Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/multimodal/multimodal-simple Cerebras' model library for implementing multimodal models ## Model Overview Multimodal Simple is our multimodal library, which can be used to instantiate many of the current state-of-the-art models such as LLaVA, CogVLM, and MM1 among others. Our implementation supports multiple images interleaved with text as input, and can generate text as output. The building blocks for this implementation are as follows: * **Vision Encoder**: Process images through one or more image encoders to produce embeddings. * **Image Embedding Projector**: Projects the embeddings from vision encoder into a shared latent space with LLM using MLPs. * **Language Model**: Accepts the vision and language embeddings as input and produces text as output. ## Structure of the code * [`configs/`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/multimodal/multimodal_simple/configs): YAML configuration files. * [`modeling_mmsimple.py`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/multimodal/multimodal_simple/modeling_mmsimple.py): Defines the core multimodal model. * [`model.py`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/multimodal/multimodal_simple/model.py): The entry point to the model. * [`run.py`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/multimodal/multimodal_simple/run.py): Training script. Performs training and validation. ## Configuration files included for this model We provide the following config files for LLaVA located under the [configs](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/multimodal/multimodal_simple/configs) directory. | Config File | Dataset | Notes | | - | - | - | | [params\_mm\_llava\_llama2\_7b\_phase1.yaml](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/multimodal/multimodal_simple/configs/params_mm_llava_llama2_7b_phase1.yaml) | [LLaVA Visual Instruct Pretrain LCS-558K Dataset](#llava-visual-instruct-pretrain-lcs-558k-dataset) | LLaVA-7B Phase-1 with CLIP ViT image encoder, Vicuna-7B text encoder and `mlp2x-gelu` Feedforward network for Projector. Freeze `image_model` and `text_model` during training | | [params\_mm\_llava\_llama2\_7b\_phase2.yaml](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/multimodal/multimodal_simple/configs/params_mm_llava_llama2_7b_phase2.yaml) | [LLaVA Visual Instruct 150K Dataset](#llava-visual-instruct-150k-dataset) | LLaVA-7B Phase-2 with CLIP ViT image encoder, Vicuna-7B text encoder and `mlp2x-gelu` Feedforward network for Projector. Freeze `image_model` during training | ## Model Training Approach A common approach to build high-quality multimodal models with limited data is to initialize the vision encoder and language models from pretrained checkpoints (for instance CLIP-VIT-L-336/14 for vision and LLaMA/Mistral/Zephyr models for language). While there are many possible recipes for training the model, the high-level goals are as follows: * **Pre-training for Feature Alignment**: This involves training the randomly-initialized projector weights to align the image features with that of the LLM embeddings. Optionally, this could also involve training all the blocks -- vision encoder, llm and projector together for further alignment of modalities. * **Instruction Fine-tuning**: In this stage, the model is trained to handle multimodal question-answering and dialogue. ## Steps to train a model The high-level steps for training this model are consistent with other models such as LLMs * Dataset preparation: Download datasets of interest and process them using our data pre-processing scripts to generate H5 files * Checkpoint preparation: Download pretrained checkpoints for vision and language models to prepare the initial checkpoint * Training: Train the model using `run.py` * Export to HF: Convert checkpoint to HF checkpoint format * Evaluation: Use standard multimodal benchmarks such lmms-eval or LLaVA source-repo ### Step 1: Dataset Prep Please follow instructions for data preprocessing in our documentation. ### Step 2: Checkpoint Prep Checkpoint converter script for converting vision encoder and LLM model checkpoints to CS format require the following directory structure: ``` /path/to/pretrained/checkpoints ├── image_model │   ├── config.json │   ├── preprocessor_config.json │   └── pytorch_model.bin └── text_model ├── config.json ├── config_lmsys.json ├── pytorch_model-00001-of-00002.bin ├── pytorch_model-00002-of-00002.bin ├── pytorch_model.bin.index.json ├── tokenizer_config.json ├── special_tokens_map.json └── tokenizer.model ``` Below, we describe how to setup CLIP + LLAMA3 8B as a LLaVA model. However, one can follow same approach to setup other vision and LLM models as well as multimodal architecture variants. a. [openai/clip-vit-large-patch14-336](https://huggingface.co/openai/clip-vit-large-patch14-336/tree/main) checkpoints, config.json and preprocessor\_config.json should be downloaded to a subdirectory `image_model`. b. [LLAMA3](https://huggingface.co/meta-llama/Meta-Llama-3-8B) checkpoints and tokenizer files should be downloaded to a subdirectory `text_model` c. Rename `config.json` to `config_lmsys.json` mv /path/to/pretrained/checkpoints/text\_model/config.json /path/to/pretrained/checkpoints/text\_model/config\_lmsys.json d. Download [LLaVA-8B config.json](https://huggingface.co/lmms-lab/llama3-llava-next-8b/blob/main/config.json) from HuggingFace We do steps (c) and (d) above since we need additional information about LLaVA model such as `mm_projector_type` etc to build appropriate CS config yaml and checkpoint ### Step 4: Convert checkpoints to CS Model Zoo format using checkpoint converter * Checkpoint conversion script: [modelzoo/tools/convert\_checkpoint.py](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/tools/convert_checkpoint.py) * LLaVA Model checkpoint converter: [modelzoo/tools/checkpoint\_converters/mm\_simple.py](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/tools/checkpoint_converters/mm_simple.py) * Command: ``` python modelzoo/tools/convert_checkpoint.py convert \ --model mm_simple \ --src-fmt hf \ --tgt-fmt cs-2.3 \ --output-dir /path/to/converted_checkpoint \ --config /path/to/pretrained/checkpoints \ /path/to/pretrained/checkpoints ``` More information about checkpoint converters can be obtained by `python modelzoo/tools/convert_checkpoint.py list` ### Step 3: Training the model on CS system using `run.py` **IMPORTANT**: See the following notes before proceeding further. **Parameter settings in YAML config file**: The config YAML files are located in the [configs](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/multimodal/multimodal_simple/configs/) directory. Before starting a training run, make sure that the YAML configs used have the following set correctly: * The `train_input.data_dir` parameter points to the correct dataset * The `train_input.img_data_dir` parameter points to the correct parent directory containing all images needed by the dataset. * The `train_input.image_size` parameter corresponds to the image-size of the dataset. * Also change sizes in `train_input.transforms` appropriately if `train_input.image_size` is updated. * The `image_model.image_size` points to the image size passed to each ViTModel * The `image_model.patch_size` parameter to use different patch sizes within each ViTModel * `model.freeze` contains the regex patterns to freeze appropriate layers in the model * `image_model.image_layer_idx` parameter to specify the image\_model encoder layer from which features are extracted for the input image. **YAML config files**: Details on the configs for this model can be found in [Configs included for this model](#configs-included-for-this-model) In the following example run commands, we use `/path/to/yaml`, `/path/to/model_dir`, and `train` as placeholders for user supplied inputs. * `/path/to/yaml` is a path to the YAML config file with model parameters such one of the configurations described in [Configs included for this model](#configs-included-for-this-model). * `/path/to/model_dir` is a path to the directory where we would like to store the logs and other artifacts of the run. * `--mode` specifies the desired mode to run the model in. Change to `--mode eval` to run in eval mode. #### To compile/validate, run train and eval on Cerebras System Please follow the instructions on our [quickstart in the Developer Docs](https://docs.cerebras.net/en/latest/wsc/getting-started/cs-appliance.html). #### To run train and eval on GPU/CPU If running on a CPU or GPU, activate the environment from [Python GPU Environment setup](../../../../../../PYTHON-SETUP.md), and simply run: ``` python run.py {CPU,GPU} \ --mode train \ --params /path/to/yaml \ --model_dir /path/to/model_dir ``` Based on your training recipe, you might choose to train the multimodal in multiple phases. Please specify the params file and model directory for each run -- this is consistent with any multi-stage training appraoch on Cerebras. ### Step 4: Convert checkpoint to source code repository format to run eval We perform evaluations on multimodal benchmarks using [LLaVA source code](https://github.com/haotian-liu/LLaVA) repository. For this, we need to convert the checkpoints generated using the training run from Phase-2 to LLaVA source code repository format. This can be done using the command: ``` python modelzoo/tools/convert_checkpoint.py convert \ --model mm_simple \ --src-fmt cs-2.3 \ --tgt-fmt hf \ --output-dir /path/to/hf_converted_checkpoint \ --config /path/to/cs_config.yaml \ /path/to/checkpoint.mdl ``` The above command generates two folders `image_model` and `text_model` under `output-dir` as shown below: ``` /path/to/converted_checkpoint ├── image_model │   ├── config.json │   ├── preprocessor_config.json │   ├── pytorch_model-00001-of-00001.bin │   └── pytorch_model.bin.index.json └── text_model ├── config.json ├── pytorch_model-00001-of-00004.bin ├── pytorch_model-00002-of-00004.bin ├── pytorch_model-00003-of-00004.bin ├── pytorch_model-00004-of-00004.bin ├── pytorch_model.bin.index.json ``` * Folder `image_model` consists of weights for `vision_tower` in source repository * Folder `text_model` consists of weights to be loaded for the Language model and projectors * The LLaVA source code repository expects tokenizer files to be present along with the language model weights ([code pointer](https://github.com/haotian-liu/LLaVA/blob/main/llava/model/builder.py#L116)). For this, **please copy the tokenizer files into `text_model` folder**. * Also, please make sure `text_model.mm_vision_tower` points to the `image_model` path to ensure the weights from `image_model` folder are loaded into the source code `vision_tower`. This path is automatically added during checkpoint conversion. * **Rename folder `text_model` to `text_model_llava`. This is since the source code repository expects the path to include `llava` keyword in order to correctly load the checkpoints. (code pointers: [builder.py](https://github.com/haotian-liu/LLaVA/blob/main/llava/model/builder.py#L48), [mm\_utils.py](https://github.com/haotian-liu/LLaVA/blob/main/llava/mm_utils.py#L207))** * So, after the relevant tokenizer files are copied, the `output-dir` should look like below: ``` /path/to/converted_checkpoint ├── image_model │   ├── config.json │   ├── preprocessor_config.json │   ├── pytorch_model-00001-of-00001.bin │   └── pytorch_model.bin.index.json └── text_model_llava ├── config.json ├── pytorch_model-00001-of-00004.bin ├── pytorch_model-00002-of-00004.bin ├── pytorch_model-00003-of-00004.bin ├── pytorch_model-00004-of-00004.bin ├── pytorch_model.bin.index.json ├── special_tokens_map.json ├── tokenizer_config.json └── tokenizer.model ``` ### Step 5: Set up source code repository for benchmark evaluation and run evaluation benchmarks * Setup LLaVA source code repository for multimodal benchmark evaluation by following instructions mentioned in [Evaluation Docs](https://github.com/haotian-liu/LLaVA/blob/main/docs/Evaluation.md). * Instructions for creating conda environment and setting up the repository are mentioned in [Installation Section](https://github.com/haotian-liu/LLaVA/blob/main/README.md#install) * Scripts to run various benchmarks are provided [here](https://github.com/haotian-liu/LLaVA/tree/main/scripts/v1_5/eval) * **Pass `text_model_llava` folder path to `--model-path` in [eval scripts in LLaVA source code repository](https://github.com/haotian-liu/LLaVA/blob/main/scripts/v1_5/eval/llavabench.sh#L4)** ## Implementation notes The following modifications and assumptions are made in this implementation: 1. This implementation brings in support for multiple images per sample, interleaving of image and text, as well as placement of images at arbitrary position within the sample. However, currently we do not have checkpoint converter for these new features since there is no one HF model that supports these multimodal features. 2. This implementation assumes that the H5 files for the dataset are created with the release 2.3 data preprocessor, and is not backward compatible with the H5 datasets produced with the previous release (2.2). 3. **We currently expect all the images under a single parent folder and the relative path of images from different datasets are written under `image_key` in the H5 files generated.** For example: ``` train_input.img_data_dir ├── coco ├── gqa ├── ocr_vqa ├── textvqa └── vg ``` ## Citations * [LLaVA-v1: Visual Instruction Tuning](https://arxiv.org/pdf/2304.08485.pdf) * [LLaVA-v1.5: Improved Baselines with Visual Instruction Tuning](https://arxiv.org/pdf/2310.03744.pdf) * [LLaVA source code repository](https://github.com/haotian-liu/LLaVA/tree/main/) * [MM1: Methods, Analysis & Insights from Multimodal LLM Pre-training](https://arxiv.org/abs/2403.09611) * [CogVLM: Visual Expert for Pretrained Language Models](https://arxiv.org/abs/2311.03079) # BLOOM Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/nlp/bloom Multilingual decoder-only language model with ALiBi positional embeddings, designed to generalize across 46 natural and 13 programming languages. ## Model Description BLOOM is a decoder-only Transformer-based language model developed by the BigScience project. It supports multilingual training across 46 natural languages and 13 programming languages, with models ranging in size up to 176B parameters. Architecturally, BLOOM resembles GPT-2 but introduces two important differences: * **Tokenizer**: BLOOM uses a tokenizer and vocabulary specifically designed for multilingual generalization, consisting of \~250K tokens. * **Position Embeddings**: Instead of learnable absolute position embeddings (as in GPT-2), BLOOM uses [ALiBi](https://arxiv.org/pdf/2108.12409.pdf) — Attention with Linear Biases — which allows extrapolation to longer sequence lengths and introduces a recency bias in attention computation. ## Code Structure The code for this model is implemented under the `bloom` directory. * [`configs/`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/bloom/configs): Contains YAML configuration files for various BLOOM variants. * [`model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt2/model.py): Shared model code reused from GPT-2, modified to support ALiBi embeddings. > [!NOTE] > > Our implementation of BLOOM is built on top of our GPT-2 backbone. For more details, see [`gpt2_model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt2/gpt2_model.py). ## Available Configurations | Configuration | Description | | - | - | | [`params_bloom_7b.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/bloom/configs/params_bloom_7b.yaml) | BLOOM-7B model with `hidden_size=4096`, `num_hidden_layers=30`, and `num_heads=32`. Uses ALiBi position embeddings. | ## Workflow For example workflows using language models from the Cerebras Model Zoo, see our tutorials on [pretraining](../../getting-started/pre-train-your-first-model) and [fine-tuning](../../getting-started/fine-tune-your-first-model). For a complete list of Cerebras ModelZoo CLI commands, see the [command reference](../../model-zoo/core-workflows/cli-reference). ## Implementation Notes The core model logic reuses components from the GPT-2 implementation, but the presence of ALiBi position embeddings enables better extrapolation to longer sequence lengths during inference. To enable this in your config file: * Set `model.position_embedding_type: alibi` * Optionally, set `model.alibi_trainable_slopes: false` (recommended, based on the ALiBi paper’s findings) ## References * [BLOOM: A 176B-Parameter Open-Access Multilingual Language Model](https://arxiv.org/abs/2211.05100) * [TRAIN SHORT, TEST LONG: Attention with Linear Biases Enables Input Length Extrapolation](https://arxiv.org/pdf/2108.12409.pdf) * [Language Models are Unsupervised Multitask Learners (GPT-2)](https://d4mucfpksywv.cloudfront.net/better-language-models/language-models.pdf) # DPO Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/nlp/dpo A simple and stable method for fine-tuning language models using human or synthetic preference data without reinforcement learning. ## Model Description Direct Preference Optimization (DPO) is a training method for fine-tuning language models using preference data — pairs of responses labeled as *preferred* vs *rejected* — without requiring reinforcement learning or a separate reward model. DPO was introduced in Rafailov et al. (2023). [Direct Preference Optimization: Your Language Model is Secretly a Reward Model](https://arxiv.org/abs/2305.18290). ## Code Structure This implementation consists of: * [`configs/`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/dpo/configs): YAML configuration files for DPO fine-tuning runs. * [`model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/dpo/model.py): Defines the DPO training logic, including the contrastive loss function used to compare chosen and rejected completions. ## Available Configurations | Configuration | Description | | - | - | | [`params_zephyr_7b_dpo.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/dpo/configs/params_zephyr_7b_dpo.yaml) | DPO training config for a 7B model using preference-labeled instruction tuning data. | ## References * Rafailov, R., et al. (2023). [Direct Preference Optimization](https://arxiv.org/abs/2305.18290) * Ouyang, L., et al. (2022). [Training language models to follow instructions with human feedback (InstructGPT)](https://arxiv.org/abs/2203.02155) * Christiano, P. et al. (2017). [Deep reinforcement learning from human preferences](https://arxiv.org/abs/1706.03741) # DPR Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/nlp/dpr Dense Passage Retrieval (DPR) model for open-domain question answering using contrastive loss between question and passage encoders. ## Model Description Dense Passage Retriever (DPR) is a technique introduced by Facebook Research that marked one of the biggest early successes in applying neural networks for retrieval. The goal of retrieval is to find passages that will help in answering a question. To accomplish this, DPR is composed of two sub-models: a question encoder, and a passage encoder. The idea is that questions and passages have different properties, so we can optimize each model (usually a BERT-based model) for each sub-domain. During training, DPR incentives the two encoders to create embeddings of questions and passages, where useful passages are close to a question in the embedding-space, and less useful passages are farther away from the question. The model uses contrastive loss to maximize the similarity of a question with its corresponding passage, and minimizes the similarity of questions with non-matching passages. We currently support DPR training on CS-X, and inference can be run on GPUs. After training, you can create embeddings for all the passages in your data using the passage encoder, and combine these into a vector database such as FAISS. The retrieval inference process is then to take a new question, run inference using the question encoder to get a question embedding, and retrieve the most similar passage embeddings from the vector database. ### Contrastive loss Contrastive loss: Contrastive loss has existed for decades, but gained popularity with the landmark paper by OpenAI paper on Contrastive Language-Image Pretraining, or CLIP. DPR uses the same technique as CLIP, but between questions and passages instead of images and captions. Since the introduction of DPR, models trained with contrastive loss have become standard for retrieval. The current state-of-the-art retrievers have remained remarkably similar to the original recipe outlined by DPR. Hard negatives: Recall that the contrastive loss paradigm tries to do two things simultaneously: (1) maximize similarity between matching question-passage pairs (positive pairs), and (2) minimize similarity between non-matching question-passage pairs (negative pairs). Neural networks use batches of data for computational efficiency, so it is common practice to exploit this in creating non-matching pairs, by comparing a question with the passage of a different question from the same batch (in-batch negatives). Some datasets will additionally add hard-negatives for each question. Creating negatives within a batch is easy and efficient; however to obtain best performance, it is best to find passages that are similar to the positive passage, but do not contain the information reqired. These passages are called hard-negatives, as it is much more difficult to discern between this negative and the true positive passage. ## Code Structure The code for DPR is structured similarly to other dual-encoder architectures and reuses BERT-style components. * [`configs/`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/dpr/configs): YAML configuration files for training DPR models. * [`model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/dpr/model.py): Defines the DPR model architecture including question and passage encoders. * [`run.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/dpr/run.py): Script for training DPR on Cerebras systems or GPU. * [`utils.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/dpr/utils.py): Utilities for config parsing and distributed training support. ## Available Configurations | Configuration | Description | | - | - | | [`params_dpr_base_nq.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/dpr/configs/params_dpr_base_nq.yaml) | Base DPR configuration trained on the Natural Questions dataset. | ## Model Input Tensor Specifications | **Input Name** | **Shape** | **Data Type** | **Description** | | - | - | - | - | | `questions_input_ids` | `(batch_size, max_seq_len)` | `torch.int32` | Token IDs for the input questions. | | `questions_attention_mask` | `(batch_size, max_seq_len)` | `torch.int32` | Attention mask for question tokens. | | `questions_token_type_ids` | `(batch_size, max_seq_len)` | `torch.int32` | Token type IDs for questions (typically all zeros). | | `ctx_input_ids` | `(batch_size, 2, max_seq_len)` | `torch.int32` | Token IDs for one positive and one hard-negative passage per question. | | `ctx_attention_mask` | `(batch_size, 2, max_seq_len)` | `torch.int32` | Attention mask for the passage tokens. | | `ctx_token_type_ids` | `(batch_size, 2, max_seq_len)` | `torch.int32` | Token type IDs for passages (typically all zeros). | ## Workflow For example workflows using language models from the Cerebras Model Zoo, see our tutorials on [pretraining](../../getting-started/pre-train-your-first-model) and [fine-tuning](../../getting-started/fine-tune-your-first-model). For a complete list of Cerebras ModelZoo CLI commands, see the [command reference](../../model-zoo/core-workflows/cli-reference). ## References * [Dense Passage Retrieval for Open-Domain Question Answering](https://arxiv.org/abs/2004.04906) * [Learning Transferable Visual Models From Natural Language Supervision (CLIP)](https://arxiv.org/pdf/2103.00020.pdf) * [The FAISS Library](https://arxiv.org/abs/2401.08281) * Diagram adapted from [PyTorch forum](https://discuss.pytorch.org/t/loss-not-decreasing-for-a-network-for-finding-related-text/114233) # ESM-2 Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/nlp/esm2 Protein language model trained on UniRef50, using a masked language modeling objective to learn evolutionary and structural properties of proteins. ## Model Description ESM-2 (Evolutionary Scale Modeling) is a family of transformer-based protein language models developed by Meta AI's Fundamental AI Research (FAIR) Protein Team. Trained on large-scale protein sequence datasets such as UniRef50, ESM-2 learns representations that encode structural and functional information about proteins without requiring evolutionary alignments. This implementation supports a range of ESM-2 model sizes, including variable sequence length (VSL) support for improved efficiency with shorter protein sequences. Models are pretrained using a masked language modeling objective similar to BERT. ## Code Structure The code for this model is located in the `esm2` directory within the ModelZoo. It reuses shared training infrastructure and custom data processors optimized for protein sequence modeling. * [`configs/`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/esm2/configs): YAML configuration files for training various ESM-2 model sizes. * [`model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/esm2/model.py): Top-level wrapper for initializing ESM-2 model instances and integrating with training. * [`esm2_pretrain_models.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/esm2/esm2_pretrain_models.py): Core model architecture implementation. * [`utils.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/esm2/utils.py): Helper utilities for config parsing and data formatting. ## Available Configurations | Configuration | Description | | - | - | | [`params_esm2_t12_35M_UR50D.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/esm2/configs/params_esm2_t12_35M_UR50D.yaml) | ESM-2 model with 12 layers and \~35M parameters. | | [`params_esm2_t33_650M_UR50D.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/esm2/configs/params_esm2_t33_650M_UR50D.yaml) | ESM-2 model with 33 layers and \~650M parameters. | | [`params_esm2_t33_650M_UR50D_vsl.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/esm2/configs/params_esm2_t33_650M_UR50D_vsl.yaml) | ESM-2 650M model with Variable Sequence Length (VSL) enabled for efficient training. | | [`params_esm2_t36_3B_UR50D.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/esm2/configs/params_esm2_t36_3B_UR50D.yaml) | ESM-2 model with 36 layers and \~3B parameters. | | [`params_esm2_t48_15B_UR50D.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/esm2/configs/params_esm2_t48_15B_UR50D.yaml) | ESM-2 model with 48 layers and \~15B parameters. | ## Workflow For example workflows using language models from the Cerebras Model Zoo, see our tutorials on [pretraining](../../getting-started/pre-train-your-first-model) and [fine-tuning](../../getting-started/fine-tune-your-first-model). For a complete list of Cerebras ModelZoo CLI commands, see the [command reference](../../model-zoo/core-workflows/cli-reference). ## References * [ESM-2: Language models for protein structure and function](https://www.science.org/doi/abs/10.1126/science.ade2574) * [UniRef50 Dataset](https://www.uniprot.org/help/uniref) # Falcon Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/nlp/falcon Series of decoder-only transformer models by TII, with 7B, 40B, and 180B parameter models ## Model Description The Falcon series consists of causal decoder-only transformer models with 7B, 40B, and 180B parameters, developed by the Technology Innovation Institute (TII). The models follow an optimized GPT-style architecture with key changes for efficient scaling and throughput: * **Parallel attention and MLP layers** within transformer blocks. * **Rotary positional embeddings (RoPE)** and **multigroup attention** (a generalization of multiquery attention) for faster inference and better tensor parallelism. * **GELU activations**, no dropout, and **z-loss regularization** for stable training. * **Context length of 2,048 tokens** and a 65K vocabulary. ## Code Structure The code for this model is located in the [`/falcon`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/falcon) directory within ModelZoo. Here’s how it’s organized: * [`/configs`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/falcon/configs): Contains YAML configuration files. * [`model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/falcon/model.py): The implementation of the Falcon model. > [!NOTE] > > Our implementation of Falcon is built on top of our GPT-2 backbone. For more details, see [`gpt2_model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt2/gpt2_model.py). ## Available Configurations | Configuration | Description | | :- | :- | | [`params_falcon_7b.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/falcon/configs/params_falcon_7b.yaml) | Falcon model with 7B parameters. | | [`params_falcon_40b.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/falcon/configs/params_falcon_40b.yaml) | Falcon model with 40B parameters. | | [`params_falcon_180b.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/falcon/configs/params_falcon_180b.yaml) | Falcon model with 180B parameters. | ## Workflow For example workflows using language models from the Cerebras Model Zoo, see our tutorials on [pretraining](../../getting-started/pre-train-your-first-model) and [fine-tuning](../../getting-started/fine-tune-your-first-model). For a complete list of Cerebras ModelZoo CLI commands, see the [command reference](../../model-zoo/core-workflows/cli-reference). ## References * The Falcon LLM Team (2023). [The Falcon Series of Open Language Models](https://arxiv.org/pdf/2311.16867) # Gemma 2 Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/nlp/gemma Decoder-only language models by Google DeepMind, using interleaved attention and GQA for high-quality performance at practical scale. ## Model Description Gemma 2 is a family of decoder-only transformer models developed by Google DeepMind, ranging from 2B to 27B parameters. Architecturally, Gemma 2 builds upon the Transformer backbone with several enhancements: it interleaves local sliding window and global attention layers, adopts grouped-query attention (GQA), and uses GeGLU activations with RMSNorm. The models support a context length of 8K and utilize a 256K-token multilingual tokenizer inherited from Gemini. Gemma 2 models are well-suited for tasks involving instruction following, long-context understanding, multilingual reasoning, and coding. ## Code Structure The code for this model is located in the [`/gemma2`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gemma2) directory within ModelZoo. Here’s how it’s organized: * [`/configs`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gemma2/configs): Contains YAML configuration files. * [`model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gemma2/model.py): The implementation of the Gemma 2 model. > [!NOTE] > > Our implementation of Gemma is built on top of our GPT-2 backbone. For more details, see [`gpt2_model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt2/gpt2_model.py). ## Available Configurations | Configuration | Description | | :- | :- | | [`params_gemma2_9b_msl8k.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gemma2/configs/params_gemma2_9b_msl8k.yaml) | 9B parameter Gemma 2 model with 8K MSL. | | [`params_gemma2_9b_msl8k_swa_4k_sink_512.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gemma2/configs/params_gemma2_9b_msl8k_swa_4k_sink_512.yaml) | Variant of the 9B model using 4K sliding window attention and 512 sink tokens. | | [`params_gemma2_27b_msl8k.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gemma2/configs/params_gemma2_27b_msl8k.yaml) | 27B parameter Gemma 2 model with 8K MSL. | ## Workflow For example workflows using language models from the Cerebras Model Zoo, see our tutorials on [pretraining](../../../getting-started/pre-train-your-first-model) and [fine-tuning](../../../getting-started/fine-tune-your-first-model). For a complete list of Cerebras ModelZoo CLI commands, see the [command reference](../../cli-overview). ## References * Gemma Team. (2024). [Gemma 2: Improving Open Language Models at a Practical Size](https://arxiv.org/abs/2408.00118) * Ainslie, J. et al. (2023). [GQA: Generalized Multi-Query Attention](https://arxiv.org/abs/2305.13245) * Hinton, G. et al. (2015). [Distilling the Knowledge in a Neural Network](https://arxiv.org/abs/1503.02531) # GPT-3 Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/nlp/gpt3 A decoder-only transformer language model, scaled to billions of parameters, trained on autoregressive next-token prediction with support for µP scaling and Cerebras-optimized workflows. ## Model Description GPT-3 is a decoder-only transformer language model architecture designed for large-scale autoregressive pretraining. It extends GPT-2 with significantly more parameters (ranging from 1.3B to 175B) and introduces architectural refinements such as sparse attention layers, used in alternating blocks to reduce compute costs during training. However, this implementation uses the GPT-2-style dense attention in all layers. Training occurs on next-token prediction using large text corpora like The PILE, with inputs represented as token sequences padded and masked to a fixed maximum sequence length. ## Code Structure The code for this model is located in the `gpt3` directory within ModelZoo. Here's how it's organized: * [`configs/`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gpt3/configs): Contains YAML configuration files for various GPT-3-sized models. * [`run.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/run.py): Training and evaluation entry point. Accepts CLI arguments for mode, config path, checkpointing, and output directories. > [!NOTE] > > Our implementation of GPT-3 is built on top of our GPT-2 backbone. For more details, see [`gpt2_model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt2/gpt2_model.py). ## Available Configurations > [accordion] Cerebras-GPT > > | Configuration | Description | > | - | - | > | [`111m.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/Cerebras_GPT/111m.yaml) | 111M parameter model using standard parametrization. | > | [`111m_mup.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/Cerebras_GPT/111m_mup.yaml) | 111M parameter model with Maximal Update Parametrization (µP). | > | [`256m.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/Cerebras_GPT/256m.yaml) | 256M parameter model using standard parametrization. | > | [`256m_mup.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/Cerebras_GPT/256m_mup.yaml) | 256M parameter model with µP. | > | [`590m.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/Cerebras_GPT/590m.yaml) | 590M parameter model using standard parametrization. | > | [`590m_mup.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/Cerebras_GPT/590m_mup.yaml) | 590M parameter model with µP. | > | [`1p3b.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/Cerebras_GPT/1p3b.yaml) | 1.3B parameter model (GPT-3 XL equivalent). | > | [`1p3b_mup.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/Cerebras_GPT/1p3b_mup.yaml) | 1.3B parameter model with µP. | > | [`2p7b.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/Cerebras_GPT/2p7b.yaml) | 2.7B parameter model. | > | [`2p7b_mup.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/Cerebras_GPT/2p7b_mup.yaml) | 2.7B parameter model with µP. | > | [`6p7b.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/Cerebras_GPT/6p7b.yaml) | 6.7B parameter model. | > | [`13b_bs720.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/Cerebras_GPT/13b_bs720.yaml) | 13B parameter model, batch size 720. | > | [`13b_bs1080.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/Cerebras_GPT/13b_bs1080.yaml) | 13B parameter model, batch size 1080. | > [accordion] Sparsity > > | Configuration | Description | > | - | - | > | [`params_gpt3_125m_rigl75.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/sparsity/pretraining/params_gpt3_125m_rigl75.yaml) | 125M parameter model with 75% sparsity using RigL pruning. | > | [`params_gpt3_125m_set75.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/sparsity/pretraining/params_gpt3_125m_set75.yaml) | 125M parameter model with 75% sparsity using SET pruning. | > | [`params_gpt3_125m_static75.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/sparsity/pretraining/params_gpt3_125m_static75.yaml) | 125M parameter model with 75% fixed sparse weights. | > | [`params_gpt3_125m_sparsewide-ift_dense.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/sparsity/pretraining/params_gpt3_125m_sparsewide-ift_dense.yaml) | 125M dense model for sparsewide-IFT comparison. | > | [`params_gpt3_125m_sparsewide-ift_rigl75.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/sparsity/pretraining/params_gpt3_125m_sparsewide-ift_rigl75.yaml) | 125M model with 75% RigL sparsity in sparsewide-IFT setup. | > | [`params_gpt3_125m_sparsewide-ift_static50.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/sparsity/pretraining/params_gpt3_125m_sparsewide-ift_static50.yaml) | 125M model with 50% static sparsity in sparsewide-IFT setup. | > | [`params_gpt3_6p7b_vspdf_phase1.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/sparsity/pretraining/params_gpt3_6p7b_vspdf_phase1.yaml) | 6.7B sparse model for VSPDF Phase 1 training. | > | [`params_gpt3_6p7b_vspdf_phase2.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/sparsity/pretraining/params_gpt3_6p7b_vspdf_phase2.yaml) | 6.7B sparse model for VSPDF Phase 2 training. | > | [`params_gpt3_6p7b_vspdf_dart.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/sparsity/finetuning/params_gpt3_6p7b_vspdf_dart.yaml) | 6.7B model with DART sparsity applied for VSPDF fine-tuning. | > [!NOTE] > > The 1.3b(xl), 2.7b, 6.7b and 13b configs above show an example of setting micro batch size explicitly in the train\_input section of the config. Without this setting, the best micro batch size search will be performed automatically during compilation which could take long time for larger models. ## Model Input Tensor Specifications | **Input Name** | **Shape** | **Data Type** | **Description** | | - | - | - | - | | `input_ids` | (batch\_size, max\_sequence\_length) | `torch.int32` | Token IDs, padded to full sequence length. | | `attention_mask` | (batch\_size, max\_sequence\_length) | `torch.int32` | 1s for valid tokens, 0s for padding. | | `labels` | (batch\_size, max\_sequence\_length) | `torch.int32` | Targets for language modeling (same as inputs). | These are generated using `GptHDF5DataProcessor.py`, which consumes PILE-formatted datasets and outputs `.h5` files via [`preprocess_data.py`](../../../data_preparation/data_preprocessing/preprocess_data.py). ## Workflow For example workflows using language models from the Cerebras Model Zoo, see our tutorials on [pretraining](../../../getting-started/pre-train-your-first-model) and [fine-tuning](../../../getting-started/fine-tune-your-first-model). For a complete list of Cerebras ModelZoo CLI commands, see the [command reference](../../cli-overview). ## Advanced Features This implementation supports: * **µP (Maximal Update Parametrization)**: For hyperparameter transfer from small proxy models to large target models.\ See [µP Tutorial](https://docs.cerebras.net/en/latest/wsc/Model-zoo/tutorials/mup/mup_docs.html). * **Cerebras-GPT Recipes**: Prebuilt configs under [`configs/Cerebras_GPT/`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/Cerebras_GPT) to reproduce results from the [Cerebras-GPT blog](https://www.cerebras.net/cerebras-gpt). ## References * [Language Models are Few-Shot Learners (GPT-3 paper)](https://arxiv.org/abs/2005.14165) * [Language Models are Unsupervised Multitask Learners (GPT-2 paper)](https://d4mucfpksywv.cloudfront.net/better-language-models/language-models.pdf) # GPT-J & GPT-Neox Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/nlp/gptj-neo Decoder-only language models by EleutherAI, designed for high-throughput training and capable zero-shot performance on a range of natural language tasks. ## Model Description GPT-J and GPT-Neox are families of decoder-only language models developed by EleutherAI and trained on the [Pile](https://arxiv.org/abs/2101.00027) dataset — a curated mixture of diverse text sources. Both models are designed to be efficient, flexible, and performant in zero-shot settings without the need for task-specific fine-tuning. ### GPT-J GPT-J is a 6B parameter auto-regressive transformer with architectural similarities to GPT-3. It introduces a parallel decoder block where attention and feed-forward layers are computed in parallel and added together, improving throughput by approximately 15% compared to traditional sequential transformer blocks. This design is especially beneficial for distributed training and single-device setups where minimizing cross-device communication is critical. GPT-J also adopts Rotary Position Embeddings (RoPE) — applying them to 25% of the features while using sinusoidal embeddings for the remainder. This hybrid approach balances convergence speed with long-context modeling capabilities. Additionally, GPT-J employs dense attention, prioritizing simplicity and training stability at this scale over sparse alternatives. ### GPT-Neox GPT-Neox shares the same architecture as GPT-J with a few refinements: * Untied LayerNorm: Each transformer block uses two independent layer normalization layers instead of a shared one. * Enhanced Tokenizer: Tokenizers were retrained on the Pile and optimized for whitespace handling, repeated tokens, and programming languages — making Neox more robust for structured text like code. These design choices allow GPT-Neox to generalize well across a broad range of domains and sequence lengths, including natural language and code generation tasks. ## Code Structure The code for these models is located in the [`/gptj`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gptj) directory within ModelZoo. Here’s how it's organized: * [`/configs`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gptj/configs): Contains YAML configuration files for GPT-J. * [`/continuous_pretraining/configs`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gptj/continuous_pretraining/configs): Contains configs for continuous pretraining of GPT-J. * [`model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gptj/model.py): The implementation of the GPT-Neox model. * [`gptneox/model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gptj/gptj_model.py): The implementation of the GPT-J model. > [!NOTE] > > Our implementations of GPT-J and GPT-Neox are built on top of our GPT-2 backbone. For more details, see [`gpt2_model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt2/gpt2_model.py). ## Available Configurations | Configuration | Description | | :- | :- | | [`params_gptj_6B.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gptj/configs/params_gptj_6B.yaml) | Standard 6B parameter GPT-J model. | | [`params_gptj_6B_muP.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gptj/configs/params_gptj_6B_muP.yaml) | GPT-J model configured with μ-parameterization for scaling. | | [`params_gptj_6B_TRC2.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gptj/configs/continuous_pretraining/configs/params_gptj_6B_TRC2.yaml) | GPT-J 6B model for continued pretraining on TRC2 datasets. | | [`params_gpt_neox_20B.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gptneox/configs/params_gpt_neox_20B.yaml) | GPT-Neox model with 20B parameters. | ## Workflow For example workflows using language models from the Cerebras Model Zoo, see our tutorials on [pretraining](../../../getting-started/pre-train-your-first-model) and [fine-tuning](../../../getting-started/fine-tune-your-first-model). For a complete list of Cerebras ModelZoo CLI commands, see the [command reference](../../cli-overview). ## References * Wang, S. et al. (2021). [Mesh-Transformer-JAX: Model-Parallel Implementation of Transformer Language Model with JAX](https://github.com/kingoflolz/mesh-transformer-jax) * Shoeybi, M. et al. (2019). [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) * Su, J. et al. (2021). [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/abs/2104.09864) * Brown, T. et al. (2020). [Language Models are Few-Shot Learners](https://arxiv.org/abs/2005.14165) * EleutherAI (2021). [Rotary Embeddings: A Relative Revolution](https://blog.eleuther.ai/rotary-embeddings/) * Black, S. et al. (2022). [GPT-NeoX-20B: An Open-Source Autoregressive Language Model](https://arxiv.org/pdf/2204.06745) # Jais Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/nlp/jais Decoder-only language models optimized for Arabic and English, developed by Inception, MBZUAI, and Cerebras. ## Model Description Jais is a family of decoder-only transformer models developed collaboratively by Inception, MBZUAI, and Cerebras. These models are trained from scratch on 395B tokens of high-quality Arabic, English, and code data, with an emphasis on cross-lingual and code-switching capabilities. Architecturally, Jais models follow the standard transformer decoder design and adopt several enhancements: they use rotary positional embeddings (RoPE), grouped-query attention (GQA), SwiGLU activations, and RMSNorm. The tokenizer is a 51.2K vocabulary SentencePiece model trained on the full multilingual corpus. The Jais family includes both base and instruction-tuned variants and is particularly well-suited for tasks involving multilingual reasoning, dialogue, and programming. ## Code Structure The code for this model is located in the [`/jais`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/jais) directory within ModelZoo. Here’s how it’s organized: * [`/configs`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/jais/configs): Contains YAML configuration files. * [`model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/jais/model.py): The implementation of the Jais model. > [!NOTE] > > Our implementation of Jais is built on top of our GPT-2 backbone. For more details, see [`gpt2_model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt2/gpt2_model.py). ## Available Configurations | Configuration | Description | | :- | :- | | [`params_jais_13b.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/jais/configs/params_jais_13b.yaml) | 13B parameter base Jais model. | | [`params_jais_13b_chat.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/jais/configs/params_jais_13b_chat.yaml) | Instruction-tuned variant of 13B. | | [`params_jais_30b.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/jais/configs/params_jais_30b.yaml) | 30B parameter base Jais model. | | [`params_jais_30b_chat.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/jais/configs/params_jais_30b_chat.yaml) | Instruction-tuned variant of 30B. | | [`params_jais_30b_phase1.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/jais/configs/params_jais_30b_phase1.yaml) | 30B checkpoint after Phase 1 pretraining. | ## Workflow For example workflows using language models from the Cerebras Model Zoo, see our tutorials on [pretraining](../../../getting-started/pre-train-your-first-model) and [fine-tuning](../../../getting-started/fine-tune-your-first-model). For a complete list of Cerebras ModelZoo CLI commands, see the [command reference](../../cli-overview). ## References * Almazrouei, E., et al. (2023). [Jais: An Open Arabic-Centric Foundation Model](https://arxiv.org/abs/2308.16149) # LLaMA Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/nlp/llama Series of decoder-only transfomer LLMs from Meta. ## Model Description The LLaMA family is a series of decoder-only transformer models designed for efficient, high-performance language modeling. Architecturally similar to GPT-2, the original LLaMA model uses RMSNorm instead of LayerNorm, SwiGLU activations, and rotary positional embeddings. LLaMA-2 improves on this with a larger training corpus, doubled context length, and grouped-query attention in its largest model. Code LLaMA specializes in programming tasks through continued pretraining on code-heavy data. LLaMA-3 introduces a more efficient 128K-token tokenizer, expands context to 8K tokens, and adopts grouped-query attention across all sizes. These models excel at text generation, summarization, reasoning, coding, and instruction following. ## Code Structure The code for this model is located in the [`/llama`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama) directory within ModelZoo. Here’s how it’s organized: * [`/configs`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama/configs): Contains YAML configuration files. * [`model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/llama/model.py): The implementation of the the LLaMA model. > [!NOTE] > > Our implementation of LLaMA is built on top of our GPT-2 implementation. For more details, see [`gpt2_model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt2/gpt2_model.py). ## Available Configurations > [accordion] LLaMa 3 > > > [tab] LLaMa 3.1 > > > > | Configuration | Description | > > | - | - | > > | [`params_llama3p1_70b_msl_128k.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama/configs/params_llama3p1_70b_msl_128k.yaml) | A 70B parameter model with a maximum sequence length of 128K, configured as described in the LLaMa 3.1 blog. | > > | [`params_llama3p1_70b_msl_8k.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama/configs/params_llama3p1_70b_msl_8k.yaml) | A 70B parameter model with a maximum sequence length of 8K, configured as described in the LLaMa 3.1 blog. | > > | [`params_llama3p1_8b_msl_128k.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama/configs/params_llama3p1_8b_msl_128k.yaml) | A 8B parameter model with a maximum sequence length of 128K, configured as described in the LLaMa 3.1 blog. | > > | [`params_llama3p1_8b_msl_32k_swa_8k_sink_512.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama/configs/params_llama3p1_8b_msl_32k_swa_8k_sink_512.yaml) | A 8B parameter model with a maximum sequence length of 32K, SWA starting at 8K, and sink tokens set to 512. Configured as described in the LLaMa 3.1 blog. | > > | [`params_llama3p1_8b_msl_8k.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama/configs/params_llama3p1_8b_msl_8k.yaml) | A 8B parameter model with a maximum sequence length of 8K, configured as described in the LLaMa 3.1 blog. | > > > [tab] LLaMa 3.2 > > > > | Configuration | Description | > > | - | - | > > | [`params_llama3p2_1b_msl_8k.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama/configs/params_llama3p2_1b_msl_8k.yaml) | A 1B parameter model with a maximum sequence length of 8K, configured as described in the LLaMa 3.2 blog. | > > | [`params_llama3p2_3b_msl_8k.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama/configs/params_llama3p2_3b_msl_8k.yaml) | A 3B parameter model with a maximum sequence length of 8K, configured as described in the LLaMa 3.2 blog. | > > > [tab] LLaMa 3.3 > > > > | Configuration | Description | > > | - | - | > > | [`params_llama3p3_70b_msl_128k.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama/configs/params_llama3p3_70b_msl_128k.yaml) | A 70B parameter model with a maximum sequence length of 128K, configured as described in the [LLaMa 3.3 model card.](https://github.com/meta-llama/llama-models/blob/main/models/llama3_3/MODEL_CARD.md) | > [accordion] LLaMa-2 > > | Configuration | Description | > | - | - | > | [`params_llama2_7b.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama/configs/params_llama2_7b.yaml) | A 7B parameter model configured as described in the [LLaMa-2 paper](https://arxiv.org/abs/2307.09288). | > | [`params_llama2_13b.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama/configs/params_llama2_13b.yaml) | A 13B parameter model configured as described in the [LLaMa-2 paper](https://arxiv.org/abs/2307.09288). | > | [`params_llama2_70b.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama/configs/params_llama2_70b.yaml) | A 70B parameter model configured as described in the [LLaMa-2 paper](https://arxiv.org/abs/2307.09288). | > [accordion] Code LLaMa > > | Configuration | Description | > | - | - | > | [`params_code_llama_7b.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama/configs/params_code_llama_7b.yaml) | A 7B parameter model configured as described in the [Code LLaMa paper](https://ai.meta.com/research/publications/code-llama-open-foundation-models-for-code/). | > | [`params_code_llama_70b.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama/configs/params_code_llama_70b.yaml) | A 70B parameter model configured as described in the [Code LLaMa paper](https://ai.meta.com/research/publications/code-llama-open-foundation-models-for-code/). | > [accordion] WizardLM > > | Configuration | Description | > | - | - | > | [`params_wizardlm_13b.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama/configs/params_wizardlm_13b.yaml) | A 13B parameter model configured as described in the [WizardLM](https://arxiv.org/pdf/2304.12244) paper. | All configs are meant to be run on Weight Streaming mode using Appliance mode and Kubernetes flow. ## Workflow For example workflows using language models from the Cerebras Model Zoo, see our tutorials on [pretraining](../../../getting-started/pre-train-your-first-model) and [fine-tuning](../../../getting-started/fine-tune-your-first-model). For a complete list of Cerebras ModelZoo CLI commands, see the [command reference](../../cli-overview). ## References * Radford, A. et al. (2019). [Language Models are Unsupervised Multitask Learners](https://d4mucfpksywv.cloudfront.net/better-language-models/language-models.pdf). * Touvron, Hugo, et al. (2023). [Llama: Open and efficient foundation language models](https://arxiv.org/pdf/2302.13971) * Touvron, Hugo, et al. (2023). [Llama 2: Open Foundation and Fine-Tuned Chat Models](https://arxiv.org/pdf/2307.09288) * Rozière, Baptiste, et al. (2023). [Code Llama: Open Foundation Models for Code](https://arxiv.org/pdf/2308.12950) * Meta AI (2024). [Build the future of AI with Meta Llama 3](https://llama.meta.com/llama3) # Mistral Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/nlp/mistral Decoder-only transformer models by Mistral, using sliding window attention and grouped-query attention for fast, high-quality language generation. ## Model Description Mistral is a family of decoder-only transformer models optimized for efficiency and throughput while preserving strong general performance. Architecturally, Mistral builds on the transformer decoder backbone with several key enhancements: it adopts grouped-query attention (GQA) for faster inference, replaces absolute positional encodings with sliding window attention for improved scalability, and utilizes SwiGLU activation functions. These models are well-suited for instruction following, reasoning, summarization, and coding tasks. Mistral is a very similar architecture to LLaMA except that: * It uses grouped-query attention (GQA), which reduces the number of attention heads for keys and values. * It applies sliding window attention (SWA) with a 4K window, enabling local attention over long sequences. * It supports a higher default maximum sequence length (MSL) of 32K, rather than LLaMA’s 4K. For more details on each technique, see the original papers in the [References section](#references). ## Code Structure The code for this model is located in the [`/mistral`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/mistral) directory within ModelZoo. Here’s how it’s organized: * [`/configs`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/mistral/configs): Contains YAML configuration files. * [`model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/mistral/model.py): The implementation of the Mistral model. > [!NOTE] > > Our implementation of Mistral is built on top of our GPT-2 implementation. For more details, see [`gpt2_model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt2/gpt2_model.py). ## Available Configurations | Configuration | Description | | :- | :- | | [`params_mistral_7B.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/mistral/configs/params_mistral_7B.yaml) | 7B parameter Mistral model. | | [`params_mistral_7B_msl128k.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/mistral/configs/params_mistral_7B_msl128k.yaml) | 7B parameter Mistral model with 128K MSL. | | [`params_mistral_12b.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/mistral/configs/params_mistral_12b.yaml) | 12B parameter Mistral model. | ## Workflow For example workflows using language models from the Cerebras Model Zoo, see our tutorials on [pretraining](../../getting-started/pre-train-your-first-model) and [fine-tuning](../../getting-started/fine-tune-your-first-model). For a complete list of Cerebras ModelZoo CLI commands, see the [command reference](../../model-zoo/core-workflows/cli-reference). ## References * Jiang, Albert, et al. (2023). [Mistral 7B](https://arxiv.org/abs/2310.06825) * Ainslie, Joshua, et al. (2023). [GQA: Training Multi-Query Transformer Models from Multi-Head Checkpoints](https://arxiv.org/abs/2305.13245) * Child, Rewon, et al. (2019). [Generating Long Sequences with Sparse Transformers](https://arxiv.org/abs/1904.10509) # Mixtral Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/nlp/mixtral Sparse Mixture of Experts models using routing and expert specialization for scalable language modeling. ## Model Description Mixtral is a family of decoder-only transformer models that use sparse Mixture of Experts (MoE) to scale model capacity without increasing inference cost. Instead of activating all model parameters for every input, Mixtral routes each token to a subset of experts — specialized feedforward networks — based on a learned or hash-based routing algorithm. This allows Mixtral models to retain training efficiency while significantly expanding total parameter count. The architecture builds on the Mistral base model, inheriting sliding window attention (SWA), grouped-query attention (GQA), SwiGLU activations, and a 32K maximum sequence length. Each expert block consists of multiple experts, and only a configurable `top_k` subset is selected per token during forward pass. Mixtral models are effective for tasks requiring high capacity — such as long-context reasoning, coding, and instruction following — while remaining efficient at inference time. ## Code Structure The code for this model is located in the [`/mixtral`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/mixtral) directory within ModelZoo. Here’s how it’s organized: * [`/configs`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/mixtral/configs): Contains YAML configuration files. * [`model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/mixtral/model.py): The implementation of the Mixtral MoE model. > [!NOTE] > > Our implementation of Mixtral is built on top of our GPT-2 implementation. For more details, see [`gpt2_model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt2/gpt2_model.py). ## Available Configurations | Configuration | Description | | :- | :- | | [`params_mixtral_8x7b.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/mixtral/configs/params_mixtral_8x7b.yaml) | Mixtral model with 8 experts of size 7B each. | | [`params_mixtral_8x22b.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/mixtral/configs/params_mixtral_8x22b.yaml) | Mixtral model with 8 experts of size 22B each. | | [`params_moe_111M_base.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/mixtral/configs/params_moe_111M_base.yaml) | Small-scale MoE model with 111M parameters. | | [`params_moe_111M_with_shared_expert.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/mixtral/configs/params_moe_111M_with_shared_expert.yaml) | 111M model with shared expert enabled. | ## Expert Configuration Details These YAML settings allow flexibility in training with different numbers of experts and levels of specialization: * `num_experts`: Defines the total number of experts in the model. * `top_k`: Specifies how many experts are selected for each token during routing. ## Additional Features for Enhanced MoE Training Our models include extra features built on top of the Mixtral base model to improve Mixture of Experts (MoE) training. These features can be configured in the YAML file: * `num_shared_experts` (Optional\[`int`]):\ Specifies the number of experts shared across all tokens. These shared experts are always activated and help capture common knowledge across different contexts. This concept is inspired by [DeepSeekMoE](https://arxiv.org/pdf/2401.06066). * `null_expert_bias` (Optional\[`float`]):\ Adds an optional bias to the "null expert" probability in the routing process, which improves loss when `top_k=1`. The null expert represents the model’s uncertainty or its decision that "none of the above" is the best option. This bias enhances gradient flow back to the router, leading to better performance. * `routing_algorithm` (Literal\[`hash`, `learned`]):\ Allows users to choose between hash-based routing and learned routing methods for determining which experts to activate. * `router_selection_nonlinearity` (Literal\[`sigmoid`, `sinkhorn`, `softmax`]):\ Specifies the type of non-linearity used in the routing algorithm to generate expert probabilities. This option is applicable when using the `"learned"` routing method. ## Workflow For example workflows using language models from the Cerebras Model Zoo, see our tutorials on [pretraining](../../getting-started/pre-train-your-first-model) and [fine-tuning](../../getting-started/fine-tune-your-first-model). For a complete list of Cerebras ModelZoo CLI commands, see the [command reference](../../model-zoo/core-workflows/cli-reference). ## References * Mistral AI. (2023). [Mixtral of Experts](https://arxiv.org/abs/2401.04088) * Shazeer, Noam, et al. (2017). [Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer](https://arxiv.org/abs/1701.06538) * DeepSeek-AI. (2024). [DeepSeekMoE](https://arxiv.org/pdf/2401.06066) # SantaCoder Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/nlp/santacoder Decoder-only language model for code generation by BigCode, trained on Java, JavaScript, and Python with support for fill-in-the-middle and multi-query attention. ## Model Description SantaCoder is a 1.1B parameter decoder-only transformer model developed by the BigCode community. It is trained on Java, JavaScript, and Python code from The Stack v1.1. Architecturally, SantaCoder uses Multi-Query Attention (MQA) for efficient inference and supports Fill-in-the-Middle (FIM) generation, allowing the model to complete and infill code based on context. It employs a 49K BPE tokenizer trained on raw bytes and achieves strong performance on MultiPL-E and HumanEval benchmarks despite being significantly smaller than competing models. SantaCoder is well-suited for code completion, interactive development tools, and multilingual code generation. ## Code Structure The code for this model is located in the [`/santacoder`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/santacoder) directory within ModelZoo. Here’s how it’s organized: * [`/configs`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/santacoder/configs): Contains YAML configuration files. * [`model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/santacoder/model.py): The implementation of the SantaCoder model. > [!NOTE] > > Our implementation of SantaCoder is built on top of our GPT-2 backbone. For more details, see [`gpt2_model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt2/gpt2_model.py). ## Available Configurations | Configuration | Description | | :- | :- | | [`params_santacoder_1b.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/santacoder/configs/params_santacoder_1b.yaml) | 1.1B parameter SantaCoder model. | ## Workflow For example workflows using language models from the Cerebras Model Zoo, see our tutorials on [pretraining](../../../getting-started/pre-train-your-first-model) and [fine-tuning](../../../getting-started/fine-tune-your-first-model). For a complete list of Cerebras ModelZoo CLI commands, see the [command reference](../../cli-overview). ## References * Ben Allal, L., et al. (2023). [SantaCoder: Don’t Reach for the Stars!](https://arxiv.org/abs/2301.03988) * Bavarian, M., et al. (2022). [Efficient Training of Language Models to Fill in the Middle](https://arxiv.org/abs/2207.14255) * Shazeer, N. (2019). [Fast Transformer Decoding: One Write-Head is All You Need](https://arxiv.org/abs/1911.02150) # StarCoder Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/nlp/starcoder Decoder-only language models for code generation by BigCode, trained on permissively licensed code with support for fill-in-the-middle and multi-query attention. ## Model Description StarCoder is a family of decoder-only transformer models developed by the BigCode initiative, optimized for high-quality code generation. The flagship model, StarCoder (15.5B), was trained on 1 trillion tokens, with an emphasis on multilingual support and strong performance in Python. Architecturally, StarCoder builds on the transformer decoder backbone with several enhancements: it uses multi-query attention (MQA) for fast inference, supports fill-in-the-middle (FIM) generation, and extends context lengths to 8K tokens. Variants of StarCoder have been fine-tuned for specific domains such as SQL, OctoPack, and WizardCoder-style instruction following. These models are well-suited for tasks such as code completion, documentation generation, and interactive programming support. ## Code Structure The code for this model is located in the [`/starcoder`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/starcoder) directory within ModelZoo. Here’s how it’s organized: * [`/configs`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/starcoder/configs): Contains YAML configuration files. * [`model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/starcoder/model.py): The implementation of the StarCoder model. > [!NOTE] > > Our implementation of StarCoder is built on top of our GPT-2 backbone. For more details, see [`gpt2_model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/gpt2/gpt2_model.py). ## Available Configurations | Configuration | Description | | :- | :- | | [`params_starcoder_15b.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/starcoder/configs/params_starcoder_15b.yaml) | Base StarCoder model with 15.5B parameters. | | [`params_octocoder_15b.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/starcoder/configs/params_octocoder_15b.yaml) | StarCoder variant fine-tuned with OctoPack-style data. | | [`params_sqlcoder_15b.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/starcoder/configs/params_sqlcoder_15b.yaml) | StarCoder variant specialized for SQL generation. | | [`params_wizardcoder_15b.yaml`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/starcoder/configs/params_wizardcoder_15b.yaml) | StarCoder variant tuned for instruction-style prompts. | ## Workflow For example workflows using language models from the Cerebras Model Zoo, see our tutorials on [pretraining](../../../getting-started/pre-train-your-first-model) and [fine-tuning](../../../getting-started/fine-tune-your-first-model). For a complete list of Cerebras ModelZoo CLI commands, see the [command reference](../../cli-overview). ## References * Li, R., et al. (2023). [StarCoder: May the Source Be With You!](https://arxiv.org/abs/2305.06161) * Ainslie, J. et al. (2023). [GQA: Generalized Multi-Query Attention](https://arxiv.org/abs/2305.13245) # T5 Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/nlp/t5 Text-to-text transformer model trained on the C4 dataset using a denoising objective, capable of performing a wide range of NLP tasks in a unified format. ## Model Description T5 (Text-To-Text Transfer Transformer) is a sequence-to-sequence model that frames all NLP tasks as text-to-text problems. Originally introduced by Raffel et al. in [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/abs/1910.10683), this model enables a single architecture to be applied across translation, summarization, classification, question answering, and more. This implementation follows the T5.1.1 variant, which focuses on self-supervised pretraining using the C4 dataset, excluding supervised datasets during pretraining. T5 modifies the standard Transformer block architecture by reordering normalization and residual connections, as illustrated below. T5's key contributions include: * Proposing a unified text-to-text format for all NLP tasks (Section 2.4) * Comparing encoder-decoder vs. decoder-only variants (Section 3.2) * Evaluating different training objectives including denoising and language modeling (Section 3.3) ## Code Structure The code for this model is located in the `t5` directory and reuses generic components for interfacing with training scripts and configuration systems. * [`configs/`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/t5/configs): YAML configuration files specifying training and model hyperparameters. * [`model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/t5/model.py): Wrapper for initializing and interfacing with the T5 model. * [`t5_model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/t5/t5_model.py): Main model implementation including encoder-decoder structure and forward logic. * [`utils.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/t5/utils.py): Utility functions for config parsing and data handling. ## Available Configurations | Configuration | Description | | - | - | | [`t5_small.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/t5/configs/t5_small.yaml) | T5-Small: `d_kv=64`, `num_heads=6`, `encoder_num_hidden_layers=8`. | | [`t5_base.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/t5/configs/t5_base.yaml) | T5-Base: `d_kv=64`, `num_heads=12`, `encoder_num_hidden_layers=12`. | | [`t5_3B.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/t5/configs/t5_3B.yaml) | T5-3B: `d_kv=128`, `num_heads=32`, `encoder_num_hidden_layers=24`. | | [`t5_11B.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/t5/configs/t5_11B.yaml) | T5-11B: `d_kv=128`, `num_heads=128`, `encoder_num_hidden_layers=24`. | ## Workflow For example workflows using language models from the Cerebras Model Zoo, see our tutorials on [pretraining](../../../getting-started/pre-train-your-first-model) and [fine-tuning](../../../getting-started/fine-tune-your-first-model). For a complete list of Cerebras ModelZoo CLI commands, see the [command reference](../../cli-overview). ## Implementation Notes This implementation includes the following deviations from the original T5.1.1 spec: 1. **Optimizer**: Adafactor is not currently supported. We use AdamW, which may lead to slightly higher final loss. 2. **Normalization**: We use `LayerNorm` instead of the originally proposed `RMSNorm` due to hardware support constraints. ## References * [Attention Is All You Need](https://arxiv.org/abs/1706.03762) * [Exploring the Limits of Transfer Learning with a Unified Text-to-text Transformer](https://arxiv.org/abs/1910.10683) * [T5v1.1 Released Checkpoints](https://github.com/google-research/text-to-text-transfer-transformer/blob/main/released_checkpoints.md#t511) * [Adam Optimizer](https://arxiv.org/abs/1412.6980) * [AdamW Optimizer](https://arxiv.org/abs/1711.05101) * [Adafactor Optimizer](https://arxiv.org/abs/1804.04235) * [RMSNorm](https://arxiv.org/abs/1910.07467) * [LayerNorm](https://arxiv.org/abs/1607.06450v1) * [An Empirical Study of Positional Encoding](https://arxiv.org/pdf/2010.04903.pdf) # Transformer Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/nlp/transformer Implementation of the original Transformer architecture introduced in "Attention Is All You Need". ## Model Description This implementation reproduces the original Transformer model architecture introduced in [Attention Is All You Need](https://arxiv.org/abs/1706.03762). It was first applied to English–German translation on the WMT16 dataset and introduced the now-standard building blocks of modern NLP models: multi-head self-attention, layer normalization, feed-forward networks, residual connections, and positional embeddings. While this implementation shares much of its foundation with the T5 model, it includes important differences in architecture, datasets, model sizes, and training objectives. In particular, this model uses learned absolute positional embeddings rather than relative encodings, and the training task is translation rather than general sequence-to-sequence learning. ## Code Structure The code for this model is located in the `transformer` directory. It reuses shared infrastructure where possible, especially components from the T5 implementation. * [`configs/`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/transformer/configs): YAML configuration files for various Transformer model sizes and training setups. * [`data_preparation/nlp/transformer/`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/data_preparation/nlp/transformer): Scripts for preprocessing the WMT16 English–German dataset. ## Available Configurations | Configuration | Description | | - | - | | [`transformer_base.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/transformer/configs/transformer_base.yaml) | Base Transformer model with `d_kv=64`, `num_heads=8`, and `encoder_num_hidden_layers=6`. | | [`transformer_large.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/nlp/transformer/configs/transformer_large.yaml) | Large Transformer model with `d_kv=64`, `num_heads=16`, and `encoder_num_hidden_layers=6`. | ## Workflow For example workflows using language models from the Cerebras Model Zoo, see our tutorials on [pretraining](../../../getting-started/pre-train-your-first-model) and [fine-tuning](../../../getting-started/fine-tune-your-first-model). For a complete list of Cerebras ModelZoo CLI commands, see the [command reference](../../cli-overview). ## Implementation Notes This implementation includes two deviations from the original Transformer paper: 1. **Optimizer**: Adafactor is not currently supported. We use AdamW instead, which may result in slightly higher final training loss. 2. **Positional Embeddings**: Learned absolute position embeddings are used rather than fixed sinusoidal embeddings. This simplification can slightly degrade performance but simplifies implementation. ## References * [Attention Is All You Need](https://arxiv.org/abs/1706.03762) * [Exploring the Limits of Transfer Learning with a Unified Text-to-text Transformer](https://arxiv.org/abs/1910.10683) * [T5v1.1 Checkpoints](https://github.com/google-research/text-to-text-transfer-transformer/blob/main/released_checkpoints.md#t511) * [Adam Optimizer](https://arxiv.org/abs/1412.6980) * [AdamW Optimizer](https://arxiv.org/abs/1711.05101) * [An Empirical Study of Positional Encoding](https://arxiv.org/pdf/2010.04903.pdf) # DINOv2 Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/vision/dino-v2 Self-supervised vision model that learns general-purpose visual features without labeled data, excelling in diverse image and pixel-level tasks ## Model Description DINOv2 is a self-supervised vision transformer model by Meta that learns high-quality image representations without needing labeled data. It builds on the success of DINO by introducing architectural and training enhancements that deliver state-of-the-art performance across various computer vision tasks, including classification. ![](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/model-zoo/dinov2-data-pipeline.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=120a042b2fce0f92d50a3b505a12f0b3) DINOv2 data processing pipeline, from Oquab et al 2023. ## Code Structure The code for this model is located in the [`dino`](https://github.com/Cerebras/modelzoo/tree/rel-2.4.2/src/cerebras/modelzoo/models/vision/dino) directory within ModelZoo. Here’s how it's organized: * [`configs/`](https://github.com/Cerebras/modelzoo/tree/rel-2.4.2/src/cerebras/modelzoo/models/vision/dino/configs): Contains YAML configuration files. * [`scripts/`](https://github.com/Cerebras/modelzoo/tree/rel-2.4.2/src/cerebras/modelzoo/models/vision/dino/scripts): Contains scripts for various workflows, including checkpoint conversion and image resizing. * [`model.py`](https://github.com/Cerebras/modelzoo/blob/rel-2.4.2/src/cerebras/modelzoo/models/vision/dino/model.py): The implementation of the DINOv2 model. * [`DinoImageDataProcessor.py`](https://github.com/Cerebras/modelzoo/blob/rel-2.4.2/src/cerebras/modelzoo/models/vision/dino/DinoImageDataProcessor.py): Data processor for DINOv2. ## Available Configurations | Configuration | Description | | - | - | | [`params_dinov2_large_224_bs1024.yaml`](https://github.com/Cerebras/modelzoo/blob/rel-2.4.2/src/cerebras/modelzoo/models/vision/dino/configs/params_dinov2_large_224_bs1024.yaml) | Config for pretraining, batch size 1024 | | [`params_dinov2_large_eval_linear.yaml`](https://github.com/Cerebras/modelzoo/blob/rel-2.4.2/src/cerebras/modelzoo/models/vision/dino/configs/params_dinov2_large_eval_linear.yaml) | Config for finetuning with downstream evaluation. | | [`params_dinov2_large_patch14_img224.yaml`](https://github.com/Cerebras/modelzoo/blob/rel-2.4.2/src/cerebras/modelzoo/models/vision/dino/configs/params_dinov2_large_patch14_img224.yaml) | Reference implementation config of DINOv2. | ## Model Input Tensor Specifications The tables below outline the expected input tensor formats for pretraining and fine-tuning. These formats are based on the configurations listed in the [Available Configurations](#available-configurations) section above. If you are using a custom configuration, you can check the tensor specifications by running: ```bash theme={null} cszoo data_processor benchmark --num_epochs 1 --steps_per_epoch 10 ``` > [tab] Pretraining > > | **Input Name** | **Shape** | **Data Type** | **Description** | > | - | - | - | - | > | `collated_masks` | (batch\_size, 2, 256) | `torch.bool` | Boolean mask indicating which patches are masked during training. | > | `global_view` | (batch\_size, 2, 3, 224, 224) | `torch.float32` | Global image views (2 samples per batch, 3-channel images of size 224x224). | > | `local_view` | (batch\_size, 8, 3, 98, 98) | `torch.float32` | Local image views (8 samples per batch, 3-channel images of size 98x98). | > [tab] Finetuning > > | **Input Name** | **Shape** | **Data Type** | **Description** | > | - | - | - | - | > | `images` | (batch\_size, 3, 224, 224) | `torch.float32` | Preprocessed images. For training, images are augmented (e.g., random resized crop, horizontal flip) and normalized; for evaluation, they are resized and center-cropped. | > | `labels` | (batch\_size,) | `torch.int32` | Ground truth labels corresponding to each input image. | ## About this Implementation This implementation of DINOv2 uses the `generic_image_encoders` architecture as its backbone. You can find the model architecture details in its [directory](https://github.com/Cerebras/modelzoo/tree/rel-2.4.2/src/cerebras/modelzoo/models/vision/generic_image_encoders). ### Differences Between Our Implementation and Meta's Unlike Meta’s version, which includes KoLeo loss, this implementation only includes DinoDistillationLoss and iBOTPatchLoss, which was introduced in DINOv2. Pretrained models from Meta and Hugging Face only include the backbone, meaning they cannot be used for continuous pretraining and are limited to downstream tasks. In contrast, our implementation provides everything needed for continuous pretraining. ## Workflow In this workflow we'll demonstrate how to get started using DINOv2, inlcuding for pretraining, continuous pretraining, and finetuning tasks. > [!NOTE] > > This workflow utilizes the ModelZoo CLI. For a list of all commands, please visit our [CLI page](https://training-docs.cerebras.ai/model-zoo/cli-overview). **1. Prerequisites and Setup** Before getting started, ensure that you've gone through our [setup and installation guide](https://training-docs.cerebras.ai/getting-started/setup-and-installation). Next, create a dedicated folder for assets (configs, data) and generated files (processed data files, checkpoints, logs, etc.): ``` mkdir dinov2 ``` > [tab] Pretraining > > Copy the sample model config for pretraining into your folder. > > ```bash theme={null} > cszoo config pull dinov2_large_224_bs1024 -o dinov2 > ``` > [tab] Continuous Pretraining > > Copy the sample model config for pretraining into your folder. > > ```bash theme={null} > cszoo config pull dinov2_large_224_bs1024 -o dinov2 > ``` > [tab] Finetuning > > Copy the sample model config for pretraining into your folder. > > ```bash theme={null} > cszoo config pull dinov2_large_eval_linear -o dinov2 > ``` **2. Data Preparation** Our implementation of DINOv2 supports all torchvision datasets. In our internal testing, we used ImageNet1K. To get started, set the dataset path to where your torchvision dataset is stored, ensuring it conforms to the torchvision standard. For more information on how to prepare datasets using `torchvision`, please visit our guide [here](https://github.com/Cerebras/monolith/tree/feacbef3c42fc6095c574deac7ed70d6c72e8ad2/src/models/src/cerebras/modelzoo/data/vision/classification/data). Once completed, your dataset directory should look as follows: ``` root_directory │-- meta.bin │-- train/ │ │-- n01440764 │ │ │-- n01440764_10026.JPEG │ │ │-- ... │ │-- n01443537 │ │ │-- ... │ │-- ... │ val/ │ │-- n01440764 │ │ │-- ILSVRC2012_val_00000946.JPEG │ │ │-- ... │ │-- n01443537 │ │ │-- ... │ │-- ... ``` > [!WARNING] > > This implementation does not support on-demand downloading, so make sure to download the dataset beforehand. Once your data directory is ready, modify the `root` parameter under `dataset` in the model config to point to the desired dataset location. **3. Running the Model** > [tab] Pretraining > > Run the pretraining process using the provided configuration. > > > [tab] CLI > > > > ```bash theme={null} > > cszoo fit dinov2/params_dinov2_large_224_bs1024.yaml \ > > --mgmt_namespace= > > ``` > > > [tab] run.py > > > > ```bash theme={null} > > python src/cerebras/modelzoo/models/vision/dino/run.py CSX \ > > --mode train \ > > --params dinov2/params_dinov2_large_224_bs1024.yaml \ > > --mount_dirs \ > > --mgmt_namespace \ > > --python_paths > > ``` > [tab] Continuous Pretraining > > In addition to pretraining from scratch, you can continue training from an existing DINOv2 checkpoint. You can do this with your own pretrained checkpoint, using Meta's checkpoints (after converting to a Cerebras-compatible format) or by using the checkpoint we provide. > > In this workflow we will use our provided pretrained checkpoint. Download it before getting started. > > ```bash theme={null} > wget -P dinov2 https://cerebras-public.s3.us-west-2.amazonaws.com/DINOv2/DINOv2Pretraining_ViTL_img224.mdl > ``` > > Once the checkpoint has finished downloading, run the model with the new checkpoint. > > > [tab] CLI > > > > ```bash theme={null} > > cszoo fit dinov2/params_dinov2_large_224_bs1024.yaml \ > > --checkpoint_path dinov2/DINOv2Pretraining_ViTL_img224.mdl \ > > --load_checkpoint model \ > > --mgmt_namespace= > > ``` > > > [tab] run.py > > > > ```bash theme={null} > > python src/cerebras/modelzoo/models/vision/dino/run.py CSX \ > > --checkpoint_path dinov2/DINOv2Pretraining_ViTL_img224.mdl \ > > --mode train \ > > --params dinov2/params_dinov2_large_224_bs1024.yaml \ > > --mount_dirs \ > > --mgmt_namespace \ > > --python_paths > > ``` > [tab] Finetuning > > To begin finetuning, update the `data_dir` parameter in your configuration file. You can find this parameter under `fit` > `train_dataloader` and `val_dataloader`. Set it to the directory containing the data you want to use for fine-tuning. > > You can finetune DINOv2 using your own pretrained checkpoint or by using the checkpoint we provide. > > To download our pretrained checkpoint: > > ``` > wget -P dinov2 https://cerebras-public.s3.us-west-2.amazonaws.com/DINOv2/DINOv2Pretraining_ViTL_img224.mdl > ``` > > Next, convert the pre-trained DINOv2 checkpoint into a ViT-compatible classification format. Since DINOv2 is a self-supervised model, it does not include a classification head by default. The conversion process extracts the ViT backbone and attaches the required classification head. > > To perform this conversion, run the `convert_dinov2_to_vit.py` script as follows: > > ```bash theme={null} > python convert_dinov2_to_vit.py \ > --input_config dinov2/params_dinov2_large_eval_linear_cszoov2.yaml \ > --output_config dinov2/finetuning_params_vit_classification.yaml \ > --dataset_path > --input_ckpt dinov2/DINOv2Pretraining_ViTL_img224.mdl > --output_ckpt dinov2/finetuning_ViTClassification_DINOv2_ViTL_img224.mdl > ``` > > Once the conversion script has finished running, open up the output configuration that was generated `finetuning_params_vit_classification.yaml` and specify the `backend` to be CSX in the `init` section as follows: > > ``` > trainer: > init: > backend: > backend_type: CSX > cluster_config: > num_csx: 1 > ``` > > > [!WARNING] > > > > The classification head is randomly initialized after the conversion, so the classification accuracy can be expected to be low at the beginning of the training run. > > ### Running Finetuning > > > [tab] CLI > > > > Once the conversion script has finished running, use the output configuration and checkpoint to train the classification head. > > > > ```bash theme={null} > > cszoo fit dinov2/finetuning_params_vit_classification.yaml \ > > --checkpoint_path dinov2/finetuning_ViTClassification_DINOv2_ViTL_img224.mdl \ > > --load_checkpoint model \ > > --mgmt_namespace= > > ``` > > > [tab] run.py > > > > Once the conversion script has finished running, use the output configuration and checkpoint to train the classification head. > > > > ```bash theme={null} > > python src/cerebras/modelzoo/models/vision/dino/run.py CSX \ > > --checkpoint_path dinov2/finetuning_ViTClassification_DINOv2_ViTL_img224.mdl \ > > --mode train \ > > --params dinov2/finetuning_params_vit_classification.yaml \ > > --mount_dirs \ #optional > > --mgmt_namespace \ > > --python_paths #optional > > ``` > > We also provide a finetuned ViT classification checkpoint that you can download and use: > > ```bash theme={null} > wget -P dinov2 https://cerebras-public.s3.us-west-2.amazonaws.com/DINOv2/ViTClassification_DINOv2_ViTL_img224.mdl > ``` ## Advanced Use Cases In addition to the workflows outlined above, we provide a number of scripts for more advanced and experimental use cases. ### Adjusting Image Size > [!WARNING] > > Our DINOv2 implementation has been tested only with an image size of 224. Using other image sizes may lead to unexpected behavior, therefore this should be considered an experimental feature. You can continue training from an existing DINOv2 checkpoint while adjusting parameters such as image size. For this purposes, we provide the `change_image_size.py` to modify the checkpoint and config. ```bash theme={null} python change_image_size.py \ --input_config dinov2/params_dinov2_large_patch14.yaml \ --input_ckpt \ --output_config dinov2/params_dinov2_continuous_pretraining.yaml \ --output_ckpt dinov2/dinov2_continuous_pretraining_chkpt.mdl \ --global_size 518 \ --local_size 224 ``` After the script finishes running, it will generate new configuration and checkpoint files. Use these files to start your training run as follows: ```bash theme={null} cszoo fit dinov2/params_dinov2_continuous_pretraining.yaml --checkpoint_path dinov2/output_config --load_checkpoint model ``` ### Configuring Per-Layer Learning Rate Schedulers As part of our DINOv2 model offering, we provide a [script](https://github.com/Cerebras/monolith/tree/rel-2.4.2/src/models/src/cerebras/modelzoo/models/vision/dino/scripts) for generating a config file that includes learning rate schedulers, following the approach used in Meta's original implementation of the model. Users can modify the learning rate settings to experiment with different schedules, but we recommend adhering to Meta’s specifications for optimal results. For a detailed explanation of Meta's training methods for DINOv2, please refer to the [paper](https://arxiv.org/pdf/2304.07193). This script should be used with the [reference implementation config](https://github.com/Cerebras/modelzoo/blob/rel-2.4.2/src/cerebras/modelzoo/models/vision/dino/configs/params_dinov2_large_patch14_img224.yaml) that is provided. It will output a configuration similar to [`params_dinov2_large_224_bs1024_cszoov2.yaml`](https://github.com/Cerebras/monolith/blob/rel-2.4.2/src/models/src/cerebras/modelzoo/models/vision/dino/configs/mz/params_dinov2_large_224_bs1024_cszoov2.yaml). **To run the script:** > [!NOTE] > > To use Meta’s predefined learning rate schedulers without modifications, simply specify only the `input_file_name` and `output_file_name` flags. ``` python /src/modelzoo/models/vision/dino/scripts/create_dinov2_config_with_schedulers.py \ --input_file_name \ --output_file_name \ --base_lr \ --batch_size \ --total_iters \ --lr_decay_rate \ --patch_emb_multiplier ``` ## References * [DINOv2: Learning Robust Visual Features without Supervision](https://arxiv.org/pdf/2304.07193) * [Emerging Properties in Self-Supervised Vision Transformers](https://arxiv.org/pdf/2104.14294) # Diffusion Transformer Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/vision/dit Vision model based on the Diffusion Transformer architecture ## Model overview This directory contains implementation for Diffusion Transformer (DiT). Diffusion Transformer\[[1](https://arxiv.org/pdf/2212.09748.pdf)], as the name suggests, belongs to the class of diffusion models. However, the key difference is that it replaces the UNet architecture backbone typically used in previous diffusion models with a Transformer backbone and some modifications. This model beats the previous diffusion models in the [FID-50K](https://papers.nips.cc/paper_files/paper/2017/file/8a1d694707eb0fefe65871369074926d-Paper.pdf) eval metric. A DiT model consists of `N` layers of DiT blocks. We support the following variants of DiT Block. More details can be found in the Section 3.2 of the paper [Diffusion Transformer](https://arxiv.org/pdf/2212.09748.pdf) and [Step 4: Training the model on CS system or GPU using `run.py`](#step-4-training-the-model-on-cs-system-or-gpu-using-run-py) In addition, we also support patch sizes of 2 (default), 4 and 8. The `Patchify` block in Figure 1 takes noised latent tensor as input from dataloader and converts into patches of size `patch_size`. The lower the patch size, the larger the number of patches (i.e maximum sequence length (MSL)) and hence larger the number of FLOPS. In order to change the patch size used, for example to `4 x 4`, set `model.patch_size: [4, 4]` in yaml configs provided. During training, an image from the dataset is taken and passed through a frozen VAE Encoder [Variational Auto Encoder](https://arxiv.org/pdf/1312.6114.pdf) to convert the image into a lower dimensional latent. Then, random gaussian noise is added to the latent tensor (Algorithm 1 of [Denoising Diffusion Implicit Models](https://hojonathanho.github.io/diffusion/assets/denoising_diffusion20.pdf)) and passed as input to the DiT .Since the [VAE Encoder](https://arxiv.org/pdf/1312.6114.pdf) is frozen and not updated during the training process, we prefetch the latents for all the images in the dataset using the script [create\_imagenet\_latents.py](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/data_preparation/vision/dit/create_imagenet_latents.py). This helps save computation and memory during the training process. Refer to Step 3. ## Structure of the code * [`configs/`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/vision/dit/configs): YAML configuration files. * [`modeling_dit.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/vision/dit/modeling_dit.py): Defines the core model `DiT`. * [`model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/vision/dit/model.py): The entry point to the model. Defines `DiTModel`. * [`utils.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/vision/dit/utils.py): Miscellaneous scripts to parse the `params` dictionary from the YAML files. * [`data/vision/diffusion/`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/data/vision/diffusion): Folder containing Dataloader and preprocessing scripts. * [`samplers/`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/vision/dit/samplers): Folder containing samplers used in Diffusion models to sample images from checkpoints. * [`layers/vae/`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/vision/dit/layers/vae): Defines VAE(Variational Auto Encoder) model layers. * [`layers/*`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/vision/dit/layers): Defines building block layers of DiT Model. * [`display_images.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/vision/dit/display_images.py): Utility script to display images in a folder in a grid format to look at all images at once. * [`pipeline.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/vision/dit/pipeline.py): Defines a DiffusionPipeline object that takes in a random gaussian input and performs sampling. * [`sample_generator.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/vision/dit/sample_generator.py): Defines a Abstract Base Class `SampleGenerator` to define sample generators for diffusion models. * [`sample_generator_dit.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/vision/dit/sample_generator_dit.py): Defines a `DiTSampleGenerator` that inherits from `SampleGenerator` class and is used to generate required number of samples from DiT Model using a given trained checkpoint. ## Available Configurations | Configuration | Description | | - | - | | [`params_dit_large_patchsize_2x2.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/vision/dit/configs/params_dit_large_patchsize_2x2.yaml) | DiT-L/2 model with \~458M parameters. Patch size 2×2, latent size 32×32×4. | | [`params_dit_xlarge_patchsize_2x2.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/vision/dit/configs/params_dit_xlarge_patchsize_2x2.yaml) | DiT-XL/2 model with \~675M parameters. Patch size 2×2, latent size 32×32×4. | | [`params_dit_2B_patchsize_2x2.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/vision/dit/configs/params_dit_2B_patchsize_2x2.yaml) | DiT-2B/2 model with \~2B parameters. Patch size 2×2, latent size 32×32×4. | ## Sequence of the steps to perform The high-level steps for training a model are relatively simple, involving data-processing and then model training and evaluation * Step 1: ImageNet dataset download and preparation * Step 2: Checkpoint Conversion of Pre-trained VAE. * Step 3: Preprocessing and saving Latent tensors from images and VAE Encoder on GPU * Step 4: Training the model on CS system or GPU using `run.py` * Step 5: Generating 50K samples from trained checkpoint on GPUs * Step 6: Using OpenAI FID evaluation repository to compute FID score. The steps are elaborated below: ### Step 1: ImageNet dataset download and preparation Inorder to download the ImageNet dataset, register on the [ImageNet website](http://image-net.org/)\[[4](https://www.image-net.org/challenges/LSVRC/2012/)]. The dataset can only be downloaded after the ImageNet website confirms the registration and sends a confirmation email. Please follow up with [ImageNet support](support@image-net.org) if a confirmation email is not received within a couple of days. Download the tar files `ILSVRC2012_img_train.tar`, `ILSVRC2012_img_val.tar`, `ILSVRC2012_devkit_t12.tar.gz` for the ImageNet dataset. Once we have all three tar files, we would need to extract and preprocess the archives into the appropriate directory structure as described below. ``` root_directory (imagenet1k_ilsvrc2012) ├── meta.bin ├── train/ │ ├── n01440764 │ │ ├── n01440764_10026.JPEG │ │ ├── n01440764_10027.JPEG │ │ ├── n01440764_10029.JPEG │ │ ├── ... │ ├── n01443537 │ │ ├── n01443537_10007.JPEG │ │ ├── n01443537_10014.JPEG │ │ ├── n01443537_10025.JPEG │ │ ├── ... │ ├── ... │ └── ... │ val/ │ ├── n01440764 │ │ ├── ILSVRC2012_val_00000946.JPEG │ │ ├── ILSVRC2012_val_00001684.JPEG │ │ └── ... │ ├── n01443537 │ │ ├── ILSVRC2012_val_00001269.JPEG │ │ ├── ILSVRC2012_val_00002327.JPEG │ │ ├── ILSVRC2012_val_00003510.JPEG │ │ └── ... │ ├── ... │ └── ... ``` Inorder to arrange the ImageNet dataset in the above format, Pytorch repository provides an easy to use script that can be found [here: https://github.com/pytorch/examples/blob/main/imagenet/extract\_ILSVRC.sh](https://github.com/pytorch/examples/blob/main/imagenet/extract_ILSVRC.sh). Download this script and invoke it as follows to preprocess the ImageNet dataset. ``` source extract_ILSVRC.sh ``` We also need a `meta.bin` file. The simplest way is to create it is to initialize `torchvision.datasets.ImageNet` once. ``` import torchvision root_dir = torchvision.datasets.ImageNet(root=root_dir, split="train") torchvision.datasets.ImageNet(root=root_dir, split="val) ``` Once the ImageNet dataset and folder are in the expected format, proceed to Step 2 ### Step 2: Checkpoint Conversion of Pre-trained VAE The next step is to convert the pretrained checkpoint provided by StabilityAI and hosted on HuggingFace to CS namespace format. This can be done using the script [vae\_hf\_cs.py](../../../data_preparation/vision/dit/vae_hf_cs.py). The script downloads the [pretrained VAE checkpoint from StabilityAI in HuggingFace](https://huggingface.co/stabilityai/sd-vae-ft-mse/resolve/main/diffusion_pytorch_model.bin) and converts to CS namespace based on model layers defined in [dit/layers/vae](./layers/vae/). For this script, we only care about the params defined under `model.vae_params` and no changes are needed except for setting the `model.vae_params.latent_size` correctly. ``` $ python modelzoo/data_preparation/vision/dit/vae_hf_cs.py -h usage: vae_hf_cs.py [-h] [--src_ckpt_path SRC_CKPT_PATH] [--dest_ckpt_path DEST_CKPT_PATH] [--params_path PARAMS_PATH] optional arguments: -h, --help show this help message and exit --src_ckpt_path SRC_CKPT_PATH Path to HF Pretrained VAE checkpoint .bin file. If not provided, file is automatically downloaded from https://huggingface.co/stabilityai/sd-vae-ft- mse/resolve/main/diffusion_pytorch_model.bin (default: None) --dest_ckpt_path DEST_CKPT_PATH Path to converted modelzoo compatible checkpoint (default: modelzoo/models/vision/dit/checkpoint_converter/mz_stabilityai-sd-vae-ft-mse_ckpt.bin) --params_path PARAMS_PATH Path to VAE model params yaml ``` Command to run: ``` python modelzoo/data_preparation/vision/dit/vae_hf_cs.py --params_path=/path/to/dit_config.yaml ``` ### Step 3: Preprocessing and saving Latent tensors from images and VAE Encoder on GPU For training the DiT model, we prefetch the latent tensor outputs from a pretrained VAE Encoder using the script [`create_imagenet_latents.py`](../../../data_preparation/vision/dit/create_imagenet_latents.py) ``` $ python modelzoo/data_preparation/vision/dit/create_imagenet_latents.py -h usage: create_imagenet_latents.py [-h] [--checkpoint_path CHECKPOINT_PATH] [--params_path PARAMS_PATH] [--horizontal_flip] --image_height IMAGE_HEIGHT --image_width IMAGE_WIDTH --src_dir SRC_DIR --dest_dir DEST_DIR [--resume] [--resume_ckpt RESUME_CKPT] [--log_steps LOG_STEPS] [--batch_size_per_gpu BATCH_SIZE_PER_GPU] [--num_workers NUM_WORKERS] [--dataset_split {train,val}] optional arguments: -h, --help show this help message and exit --checkpoint_path CHECKPOINT_PATH Path to VAE model checkpoint (default: None) --params_path PARAMS_PATH Path to VAE model params yaml (default:modelzoo/models/vision/dit/configs/params_dit_small_patchsize_2x2.yaml) --horizontal_flip If passed, flip image horizonatally (default: False) --image_height IMAGE_HEIGHT Height of the resized image --image_width IMAGE_WIDTH Width of the resized image --src_dir SRC_DIR source data location (default: None) --dest_dir DEST_DIR Latent data location (default: None) --resume If specified, resumes previous generation process.The dest_dir should point to previous generation and have log_checkpoint saved. (default: False) --resume_ckpt RESUME_CKPT log ckpt to resume data generation fromIf None, picks latest from log dir (default: None) --log_steps LOG_STEPS Generation process ckpt and logging frequency (default: 1000) --batch_size_per_gpu BATCH_SIZE_PER_GPU batch size of input to be passed to VAE model for encoding (default: 64) --num_workers NUM_WORKERS Number of pytorch dataloader workers (default: 4) --dataset_split {train,val} Number of pytorch dataloader workers (default: train) ``` Inorder to preprocess the ImageNet dataset and create latent tensors, **using a GPU or multiple GPUs is required**. Sample command is as follows for a single node with 4 GPUs. In the following command, we are using an image of size 256 x 256 and saving the latents to a folder specified by `--dest_dir`. The command also specifies to log every 10 steps and use a batch size of 16 i.e 16 images are batched together and passed to the VAE Encoder on each GPU. ##### a. Create ImageNet Latent Tensors from VAE for `train` split of dataset ``` torchrun --nnodes 1 --nproc_per_node 4 modelzoo/data_preparation/vision/dit/create_imagenet_latents.py --image_height=256 --image_width=256 --src_dir=/path/to/imagenet1k_ilsvrc2012 --dest_dir=/path_to_dest_dir --log_steps=10 --dataset_split=train --batch_size_per_gpu=16 --checkpoint_path=/path/to/converted/vae_checkpoint/in_Step2 ``` ##### b. Create ImageNet Latent Tensors from VAE for `val` split of dataset ``` torchrun --nnodes 1 --nproc_per_node 4 modelzoo/data_preparation/vision/dit/create_imagenet_latents.py --image_height=256 --image_width=256 --src_dir=/path/to/imagenet1k_ilsvrc2012 --dest_dir=/path_to_dest_dir --log_steps=10 --dataset_split=val --batch_size_per_gpu=16 --checkpoint_path=/path/to/converted/vae_checkpoint/in_Step2 ``` The output folder shown below for reference and will have the same format as shown in Step 1: ``` /path_to_dest_dir ├── train/ │ ├── n01440764 │ │ ├── n01440764_10026.npz │ │ ├── n01440764_10027.npz │ │ ├── n01440764_10029.npz │ │ ├── ... │ ├── n01443537 │ │ ├── n01443537_10007.npz │ │ ├── n01443537_10014.npz │ │ ├── n01443537_10025.npz │ │ ├── ... │ ├── ... │ └── ... │ val/ │ ├── n01440764 │ │ ├── ILSVRC2012_val_00000946.npz │ │ ├── ILSVRC2012_val_00001684.npz │ │ └── ... │ ├── n01443537 │ │ ├── ILSVRC2012_val_00001269.npz │ │ ├── ILSVRC2012_val_00002327.npz │ │ ├── ILSVRC2012_val_00003510.npz │ │ └── ... │ ├── ... │ └── ... ``` DiT models use horizontal flip of images as augmentation. The script also supports saving latent tensors from horizontally flipped images by passing the flag `--horizontal_flip` ##### c. Create ImageNet Latent Tensors with horizontal flip from VAE for `train` split of dataset ``` torchrun --nnodes 1 --nproc_per_node 4 modelzoo/data_preparation/vision/dit/create_imagenet_latents.py --image_height=256 --image_width=256 --src_dir=/path/to/imagenet1k_ilsvrc2012 --dest_dir=/path_to_hflipped_dest_dir --log_steps=10 --dataset_split=train --batch_size_per_gpu=16 --checkpoint_path=/path/to/converted/vae_checkpoint/in_Step2 --horizontal_flip ``` ##### d. Create ImageNet Latent Tensors with horizontal flip from VAE for `val` split of dataset ``` torchrun --nnodes 1 --nproc_per_node 4 modelzoo/data_preparation/vision/dit/create_imagenet_latents.py --image_height=256 --image_width=256 --src_dir=/path/to/imagenet1k_ilsvrc2012 --dest_dir=/path_to_hflipped_dest_dir --log_steps=10 --dataset_split=val --batch_size_per_gpu=16 --checkpoint_path=/path/to/converted/vae_checkpoint/in_Step2 --horizontal_flip ``` ### Step 4: Training the model on CS system or GPU using `run.py` **IMPORTANT**: See the following notes before proceeding further. **Parameter settings in YAML config file**: The config YAML files are located in the [configs](configs/) directory. Before starting a training run, make sure that in the YAML config file being used has the following set correctly: * The `train_input.data_dir` parameter points to the correct dataset * The `train_input.image_size` parameter corresponds to the image\_size of the dataset. * The `model.vae.latent_size` parameter corresponds size of latent tensors. * Set to `[32, 32]` for image size of `256 x 256` * Set to `[64, 64]` for image size of `512 x 512` * In general, set to `[floor(H / 8), floor(W / 8)]` for an image size of `H x W` * The `model.patch_size` parameter to use different patch sizes **To use with image size `512 x 512`, please make the following changes:** 1. `train_input.image_size`: \[512, 512] 2. `model.vae.latent_size`: \[64, 64] 3. `train_input.transforms`(if any): change `size` params under various transforms to \[512, 512] **YAML config files**: Details on the configs for this model can be found in [Configs included for this model](#configs-included-for-this-model) In the following example run commands, we use `/path/to/yaml`, `/path/to/model_dir`, and `train` as placeholders for user supplied inputs. * `/path/to/yaml` is a path to the YAML config file with model parameters such one of the configurations described in [Configs included for this model](#configs-included-for-this-model). * `/path/to/model_dir` is a path to the directory where we would like to store the logs and other artifacts of the run. * `--mode` specifies the desired mode to run the model in. Change to `--mode eval` to run in eval mode. #### To compile/validate, run train and eval on Cerebras System Please follow the instructions on our [quickstart in the Developer Docs](https://docs.cerebras.net/en/latest/wsc/getting-started/cs-appliance.html). #### To run train and eval on GPU/CPU If running on a cpu or gpu, activate the environment from [Python GPU Environment setup](../../../../../../PYTHON-SETUP.md), and simply run: ``` python run.py {CPU,GPU} --mode train --params /path/to/yaml --model_dir /path/to/model_dir ``` ### Step 5: Generating 50K samples from trained checkpoint on GPUs from FID score computation Diffusion models report Fréchet inception distance (FID)[\[7\]](https://papers.nips.cc/paper_files/paper/2017/file/8a1d694707eb0fefe65871369074926d-Paper.pdf) metric on 50K samples generated from the trained checkpoint. In order to generate samples, we use a DDPM Sampler \[[2](https://hojonathanho.github.io/diffusion/assets/denoising_diffusion20.pdf)] and without guidance (`model.reverse_process.guidance_scale=1.0`). Using a `model.reverse_process.guidance_scale >1.0` enables classifier free guidance which trades off diversity for sample quality. The sample generation settings can be found in `model.reverse_params` in config yaml. We support two samplers cuurently, the [DDPM Sampler](./samplers/DDPMSampler.py)\[[2](https://hojonathanho.github.io/diffusion/assets/denoising_diffusion20.pdf)] and [DDIM Sampler](./samplers/DDIMSampler.py)\[[3](https://arxiv.org/pdf/2010.02502.pdf)]. All arguments in the `__init__` of the samplers can be set in the yaml config `model.reverse_params.sampler` section. To generate samples from a trained DiT checkpoint, we use GPUs and [sample\_generator\_dit.py](./sample_generator_dit.py). Sample command to run on a single node with 4 GPUs to generate 50000 samples using trained DiT-XL/2. Each GPU uses a batch size of 64 and generates 64 samples at once. `--num_fid_samples` controls the number of samples to generate. This script cares about the section `model.reverse_params` in config yaml. Make sure that the settings are appropriate. ``` torchrun --nnodes 1 --nproc_per_node 4 modelzoo/models/vision/dit/sample_generator_dit.py --model_ckpt_path /path/to/trained/dit_checkpoint --vae_ckpt_path /path/to/converted/vae_checkpoint/in_Step2 --params modelzoo/models/vision/dit/configs/params_dit_xlarge_patchsize_2x2.yaml --sample_dir=/path/to/store/samples_generated --num_fid_samples=50000 --batch_size 64 ``` More information can be found by running: ``` python modelzoo/models/vision/dit/sample_generator_dit.py -h usage: sample_generator_dit.py [-h] [--seed SEED] [--model_ckpt_path MODEL_CKPT_PATH] [--vae_ckpt_path VAE_CKPT_PATH] --params PARAMS [--variant VARIANT] [--num_fid_samples NUM_FID_SAMPLES] --sample_dir SAMPLE_DIR [--batch_size BATCH_SIZE] [--create_grid] optional arguments: -h, --help show this help message and exit --seed SEED --model_ckpt_path MODEL_CKPT_PATH Optional path to a diffusion model checkpoint (default: None) --vae_ckpt_path VAE_CKPT_PATH Optional VAE model checkpoint path (default: None) --params PARAMS Path to params to initialize Diffusion model and VAE models (default: None) --variant VARIANT Variant of Diffusion model (default: None) --num_fid_samples NUM_FID_SAMPLES number of samples to generate (default: 50000) --sample_dir SAMPLE_DIR Directory to store generated samples (default: None) --batch_size BATCH_SIZE per-gpu batch size for forward pass (default: None) --create_grid If passed, create a grid from images generated (default: False) ``` **The script generates a `.npz` file that should be passed as input to FID score computation. Sample output looks as below:** ``` 2023-09-06 15:55:30,585 INFO[sample_generator.py:49] Saved .npz file to /path/to/store/samples_generated/sample.npz [shape=(`num_fid_samples`, train_input.image_shape[0], train_input.image_shape[1], train_input.image_channels )]. ``` To generate samples belonging to specific ImageNet label classes, please set `model.reverse_params.pipeline.custom_labels` to a list of integer ImageNet labels. This will generate samples belonging to only these classes. For ex: if `model.reverse_params.pipeline.custom_labels: [207, 360]`, then we will only generate samples belonging to `golden_retriever`(label\_id=207) and `otter`(label\_id=360) classes respectively. ### Step 6: Using OpenAI FID evaluation repository to compute FID score Now that we have the 50K samples and `.npz` file generated from Step 5, we can compute FID score using ADM OpenAI script [evaluator.py](https://github.com/openai/guided-diffusion/blob/main/evaluations/evaluator.py). In order to compute FID score, #### a. Set up a conda environment to use OpenAI evaluation script ``` conda create --name tf python=3.8.16 conda activate tf conda install -c conda-forge cudatoolkit=11.8.0 pip install nvidia-cudnn-cu11==8.6.0.163 CUDNN_PATH=$(dirname $(python -c "import nvidia.cudnn;print(nvidia.cudnn.__file__)")) export LD_LIBRARY_PATH=$CONDA_PREFIX/lib/:$CUDNN_PATH/lib:$LD_LIBRARY_PATH pip install --upgrade pip pip install tensorflow==2.13.* conda install scipy conda install -c conda-forge tqdm conda install -c anaconda requests conda install -c anaconda chardet ``` #### b. Clone [OpenAI guided-diffusion GitHub repository](https://github.com/openai/guided-diffusion/tree/main) ``` git clone https://github.com/openai/guided-diffusion.git cd guided-diffusion/evaluations ``` #### c. Download the `npz` files corresponding to reference batch of ImageNet ``` wget https://openaipublic.blob.core.windows.net/diffusion/jul-2021/ref_batches/imagenet/256/VIRTUAL_imagenet256_labeled.npz -P /path/to/store/reference_batch ``` #### d. Make changes to `evaluator.py` Make the following changes in [evaluator.py](https://github.com/openai/guided-diffusion/blob/main/evaluations/evaluator.py). These are needed to account for [numpy deprecations](https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations) i.e replace instances of `np.bool` with bool ``` [evaluations](main)$ git diff diff --git a/evaluations/evaluator.py b/evaluations/evaluator.py index 9590855..6636d0b 100644 --- a/evaluations/evaluator.py +++ b/evaluations/evaluator.py @@ -340,8 +340,8 @@ class ManifoldEstimator: - precision: an np.ndarray of length K1 - recall: an np.ndarray of length K2 """ - features_1_status = np.zeros([len(features_1), radii_2.shape[1]], dtype=np.bool) - features_2_status = np.zeros([len(features_2), radii_1.shape[1]], dtype=np.bool) + features_1_status = np.zeros([len(features_1), radii_2.shape[1]], dtype=bool) + features_2_status = np.zeros([len(features_2), radii_1.shape[1]], dtype=bool) for begin_1 in range(0, len(features_1), self.row_batch_size): end_1 = begin_1 + self.row_batch_size batch_1 = features_1[begin_1:end_1] ``` #### e. Launch FID eval script with the following command ``` conda activate tf cd guided-diffusion/evaluations python evaluator.py /path/to/step(d)/downloaded/VIRTUAL_imagenet256_labeled.npz /path/to/generated/npz/from/step5 2>&1 | tee fid.log ``` The following changes can be made to use other settings of DiT model: * The `model.vae.latent_size` parameter corresponds size of latent tensors. **This is the only param under `model.vae_params` that needs to be changed.** * Set to `[32, 32]` for image size of `256 x 256` * Set to `[64, 64]` for image size of `512 x 512` * Set to `[floor(H / 8), floor(W / 8)]` for image size of `H x W` * The `model.patch_size` parameter to use different patch sizes ## DataLoader Features Dictionary [DiffusionLatentImageNet1KProcessor](../../../data/vision/diffusion/DiffusionLatentImageNet1KProcessor.py) outputs the following features dictionary with keys/values: * `input`: Noised latent tensor. * Shape: `(batch_size, model.vae.latent_channels, model.vae.latent_size[0], model.vae.latent_size[1])` * Type: `torch.bfloat16` * `label`: Scalar ImageNet labels. * Shape: `(batch_size, )` * Type: `torch.int32` * `diffusion_noise`: Gaussian noise that the model should predict. Also used in creating value of key `noised_latent`. * Shape: `(batch_size, model.vae.latent_channels, model.vae.latent_size[0], model.vae.latent_size[1])` * Type: `torch.bfloat16` * `timestep`: Timestep sampled from *\~Uniform(0, `train_input.num_diffusion_steps`)*. * Shape: `(batch_size, )` * Type: `torch.int32` ## Implementation notes There are a couple modifications to the DiT model made in this implementation: 1. We use `ConvTranspose2D` instead of `Linear` layer to un-patchify the outputs. 2. While we support `gelu with approximation tanh`, we use `gelu with no approximation` for better performance. 3. Inorder to use the exact model as [StabilityAI pretrained VAE model](https://huggingface.co/stabilityai/sd-vae-ft-mse/resolve/main/diffusion_pytorch_model.bin), we don't have to make any changes to the params under `model.vae_params`. The only modification we make in our implementation of VAE Model is that we use [Attention Layer defined in modelzoo](../../../layers/AttentionLayer.py). 4. We currently do not support Kullback-Leibler(KL) loss to optimize Σ, hence the output from DiT Model includes only the noise. 5. We currently support `AdaLN-Zero` variant of DiT model. Support for `In-Context` and `Cross-Attention` variants are planned for future releases. ## Citations \[1] [Scalable Diffusion Models with Transformers](https://arxiv.org/pdf/2212.09748.pdf) \[2] [Denoising Diffusion Probabilistic Models](https://hojonathanho.github.io/diffusion/assets/denoising_diffusion20.pdf) \[3] [Denoising Diffusion Implicit Models](https://arxiv.org/pdf/2010.02502.pdf) \[4] [ImageNet Large Scale Visual Recognition Challenge](https://www.image-net.org/challenges/LSVRC/2012/) \[5] [Diffusion Models Beat GANs on Image Synthesis](https://arxiv.org/pdf/2105.05233.pdf) \[6] [Guided Diffusion GitHub](https://github.com/openai/guided-diffusion) \[7] [GANs Trained by a Two Time-Scale Update Rule Converge to a Local Nash Equilibrium](https://papers.nips.cc/paper_files/paper/2017/file/8a1d694707eb0fefe65871369074926d-Paper.pdf) \[8] [Auto-Encoding Variational Bayes](https://arxiv.org/pdf/1312.6114.pdf) # ViT Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/models/vision/vit Implementation of Vision Transformers (ViT) for image classification on ImageNet-1K. ## Model Description The Vision Transformer (ViT) architecture applies transformer-based modeling, originally developed for NLP, to sequences of image patches for visual tasks. Instead of using convolutional layers, ViT treats an image as a sequence of non-overlapping patches, embeds them, and feeds them into a standard transformer encoder. This implementation supports ViT models of various sizes trained on ImageNet-1K and provides flexible configuration options for patch sizes, model depth, and hidden dimensions. The transformer layers operate over patch embeddings with added positional information, enabling strong performance in image classification tasks when pretrained on large datasets. ## Code Structure The code for this model is located in the `vit` directory within ModelZoo. Here’s how it's organized: * [`configs/`](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/vision/vision_transformer/configs): Contains YAML configuration files for different ViT variants. * [`model.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/vision/vision_transformer/model.py): Entry point that initializes and builds the model components used for training and evaluation. * [`ViTModel.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/vision/vision_transformer/ViTModel.py): Core implementation of the ViT architecture, including patch embedding, transformer encoder blocks, and classification head. * [`ViTClassificationModel.py`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/vision/vision_transformer/ViTClassificationModel.py): Wraps `ViTModel` for classification tasks, managing preprocessing, logits generation, and loss computation. ## Available Configurations | Configuration | Description | | - | - | | [`params_vit_base_patch_16_imagenet_1k.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/vision/vit/configs/params_vit_base_patch_16_imagenet_1k.yaml) | ViT-Base model with 16×16 patch size trained on ImageNet-1K. | | [`params_vit_huge_patch_16_imagenet_1k.yaml`](https://github.com/Cerebras/modelzoo/blob/main/src/cerebras/modelzoo/models/vision/vit/configs/params_vit_huge_patch_16_imagenet_1k.yaml) | ViT-Huge model with 16×16 patch size trained on ImageNet-1K. | ## References * [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929) # Trainer Configuration Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/trainer-configuration-overview Learn how to set up and customize the Trainer using a YAML configuration file. The Model Zoo includes helpful tools to simplify model training—one of which is the ability to configure the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html "cerebras.modelzoo.Trainer") class using a YAML file. This page walks you through how to create and customize a YAML configuration for the Trainer. By the end, you’ll understand the key parameters and be ready to write your own configuration files from scratch. ## Prerequisites Please ensure that you have read through [Trainer Essentials](../model-zoo/trainer-overview) beforehand. The rest of this page assumes that you already have at least a cursory understanding of what the Trainer is and how to use the Python API. ## Base Specification The YAML specification is intentionally designed to map almost exactly one-to-one with the Trainer’s python API. The Trainer’s constructor can be specified via a YAML configuration file as follows: ```yaml YAML theme={null} trainer: init: device: "CSX" model_dir: "./model_dir" model: # The remaining arguments to the model class vocab_size: 1024 max_position_embeddings: 1024 ... optimizer: # Corresponds to cstorch.optim.SGD SGD: lr: 0.01 momentum: 0.9 loop: num_steps: 1000 eval_steps: 100 eval_frequency: 100 checkpoint: steps: 100 fit: train_dataloader: data_processor: GptHDF5MapDataProcessor data_dir: "/path/to/train/data" batch_size: 64 ... val_dataloader: data_processor: GptHDF5MapDataProcessor data_dir: "/path/to/validation/data" batch_size: 64 ... ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import Checkpoint, TrainingLoop from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model from cerebras.modelzoo.data.nlp.gpt.GptHDF5MapDataProcessor import GptHDF5MapDataProcessor trainer = Trainer( device="CSX", # The device to run on model_dir="./model_dir", # The directory at which to store artifacts model=lambda: Gpt2Model( vocab_size=1024, max_position_embeddings=1024, ... ), optimizer=lambda model: cstorch.optim.SGD( model.parameters(), lr=0.01, momentum=0.9 ), loop=TrainingLoop(num_steps=1000, eval_steps=100, eval_frequency=100), checkpoint=Checkpoint(steps=100), ) trainer.fit( train_dataloader=cstorch.utils.data.DataLoader( GptHDF5MapDataProcessor, data_dir="/path/to/train/data", batch_size=64, ..., ), val_dataloader=cstorch.utils.data.DataLoader( GptHDF5MapDataProcessor, data_dir="/path/to/validation/data", batch_size=64, ..., ), ) ``` Click the Python tab above to see the equivalent Python code for the YAML configuration. The YAML closely mirrors the Python API by design, making it easy to switch between the two if you're familiar with either. ## Config Parameters The YAML specification starts with the top level `trainer` key. ```bash theme={null} trainer: ... ``` If this key is not present, then the configuration is not valid. The `trainer` accepts the following subkeys: * [`init`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html#cerebras.modelzoo.Trainer) * [`fit`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html?highlight=fit#cerebras.modelzoo.Trainer.fit) * [`validate`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html?highlight=fit#cerebras.modelzoo.Trainer.validate) * [`validate_all`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html?highlight=fit#cerebras.modelzoo.Trainer.validate_all) ### init The [`init`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html#cerebras.modelzoo.Trainer) key is used to specify the arguments to the Trainer’s constructor as key-value pairs, where the key is the argument name and the value is the argument value. Below are all of the accepted keys alongside YAML examples and their equivalent Python counterparts: #### device The device to train the model on. If provided, it must be one of `"CSX"`, `"CPU"`, or `"GPU"`. ```yaml YAML theme={null} trainer: init: device: "CSX" ... ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer trainer = Trainer( device="CSX", ..., ) ... ``` #### backend Configures the backend used to train the model. If provided, it is expected to be a dictionary whose keys will be used to construct a [`cerebras.pytorch.backend`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html#backend) instance. ```yaml YAML theme={null} trainer: init: backend: backend_type: "CSX" cluster_config: num_csx: 4 mount_dirs: - /path/to/dir1 - /path/to/dir2 ... ... ... ... ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( backend=cstorch.backend( backend_type="CSX", cluster_config=cstorch.distributed.ClusterConfig( num_csx=4, mount_dirs=["/path/to/dir1", "/path/to/dir2"], ..., ), ..., ) ... ) ... ``` > [!NOTE] > > The `backend` argument is mutually exclusive with `device`. The functionality it provides is a strict superset of the functionality provided by `device`. To use a certain backend with all default parameters, you may specify `device`. To configure anything about the backend, you must specify those parameters via the `backend` key. > > To learn more about the backend argument, you can check out [Trainer Backend](../model-zoo/components/trainer-components/backend). #### model\_dir The directory where the model artifacts are saved. Some of the artifacts that may be dumped into the `model_dir` include (but are not limited to): * Client-side logs * Checkpoints * TensorBoard event files * Tensor summaries * Validation results ```yaml YAML theme={null} trainer: init: ... model_dir: "./model_dir" ... ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer trainer = Trainer( ..., model_dir="./model_dir", ..., ) ... ``` #### model Configures the [`Module`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) to train/validate using the constructed Trainer. All subkeys are passed as arguments to the model class. ```yaml YAML theme={null} trainer: init: ... model: vocab_size: 1024 max_position_embeddings: 1024 ... ... ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.models.nlp.gpt2.model import Gpt2Model trainer = Trainer( ..., model=lambda: Gpt2Model( vocab_size=1024, max_position_embeddings=1024, ..., ), ..., ) ... ``` To learn more about the model argument, you can check out [Trainer Model](../model-zoo/components/trainer-components/model). #### optimizer Configures the [`Optimizer`](../model-zoo/components/trainer-components/optimizer-and-scheduler) to use to optimize the model’s weights during training. The value at this key is expected to be a dictionary. This dictionary is expected to contain a single key that specifies the name of the Cerebras optimizer to construct. That is to say, it must be the name of a subclass of [`Optimizer`](../model-zoo/components/trainer-components/optimizer-and-scheduler) subclasses that come packaged in `cerebras.pytorch`) The value of the Optimizer name key is expected to be dictionary of key-value pairs that correspond to the arguments of the optimizer subclass. ```yaml YAML theme={null} trainer: init: ... optimizer: # Corresponds to cstorch.optim.SGD SGD: lr: 0.01 momentum: 0.9 ... ... ``` > [!NOTE] > > The `params` argument to the optimizer is automatically passed in and thus is not required. ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( ..., optimizer=lambda model: cstorch.optim.SGD( model.parameters(), lr=0.01, momentum=0.9, ), ..., ) ... ``` To learn more about the optimizer argument, you can check out [Trainer Optimizer](../model-zoo/components/trainer-components/optimizer-and-scheduler). #### schedulers Configures the [`Scheduler`](../model-zoo/components/trainer-components/optimizer-and-scheduler) instances to use during the training run. The value at this key is expected to be a dictionary or a list of dictionaries. Each dictionary is expected to have a single key specifying the name of the `Scheduler` to use. The corresponding value of the Scheduler name key is expected to be mapping of key-value pairs that are passed as keyword arguments to the Scheduler. > [!NOTE] > > The optimizer argument to the Scheduler is automatically passed in and thus is not required. ```yaml YAML theme={null} trainer: init: ... schedulers: - LinearLR: initial_learning_rate: 0.01 end_learning_rate: 0.001 total_iters: 100 ... ... ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( ..., schedulers=[ lambda optimizer: cstorch.optim.lr_scheduler.LinearLR( optimizer, initial_learning_rate=0.01, end_learning_rate=0.001, total_iters=100, ), ... ], ..., ) ... ... ``` To learn more about the schedulers argument, you can check out [Trainer Schedulers](../model-zoo/components/trainer-components/optimizer-and-scheduler). #### precision Configures [`Precision`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/optim.html#cerebras.pytorch.optim.Optimizer). Today, the only supported `Precision` type is [`MixedPrecision`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html?highlight=mixedprecision#cerebras.modelzoo.trainer.callbacks.MixedPrecision). So, the value of the `precision` key is expected to be a dictionary corresponding to the arguments of `MixedPrecision`. ```yaml YAML theme={null} trainer: init: ... precision: fp16_type: float16 precision_opt_level: 1 loss_scaling_factor: dynamic max_gradient_norm: 1.0 ... ... ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import MixedPrecision trainer = Trainer( ..., precision=MixedPrecision( fp16_type="float16", precision_opt_level=1, loss_scaling_factor="dynamic", max_gradient_norm=1.0, ..., ), ..., ) ... ``` To learn more about the precision argument, you can check out [Trainer Precision](../model-zoo/api/cerebras-modelzoo/cerebras-modelzoo). #### sparsity Configures the [`SparsityAlgorithm`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html?highlight=sparsityalgorithm#cerebras.pytorch.sparse.SparsityAlgorithm) to use to sparsity the model’s weights and optimizer state. The value at this key is expected to be a dictionary. At a minimum, this dictionary is expected to contain an `algorithm` key that specifies the name of the sparsity algorithm to apply as well as a `sparsity` that specifies the level of sparsity to apply. ```yaml YAML theme={null} trainer: init: ... sparsity: algorithm: Static sparsity: 0.5 ... ... ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( ..., sparsity=cstorch.sparse.Static( sparsity=0.5, ), ..., ) ... ``` To learn more about how sparsity can be configured, see [Train a Model with Weight Sparsity](../model-zoo/tutorials/train-a-model-with-weight-sparsity). #### loop Configures a [`TrainingLoop`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html?highlight=trainingloop#cerebras.modelzoo.trainer.callbacks.TrainingLoop) instance that specifies how many steps to train and validate for. ```yaml YAML theme={null} trainer: init: ... loop: num_steps: 1000 eval_steps: 100 eval_frequency: 100 ... ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import TrainingLoop trainer = Trainer( ..., loop=TrainingLoop( num_steps=1000, eval_steps=100, eval_frequency=100, ), ..., ) ... ``` To learn more about the loop argument, you can check out [Training Loop](../model-zoo/components/trainer-components/loop). #### checkpoint Configures a [`Checkpoint`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#checkpoint) instance that specifies how frequently the trainer should save checkpoints during training. ```yaml YAML theme={null} trainer: init: ... checkpoint: steps: 100 ... ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import Checkpoint trainer = Trainer( ..., loop=Checkpoint( steps=1000, ), ..., ) ... ``` To learn more about the checkpoint argument, you can check out [Checkpointing](../model-zoo/components/trainer-components/checkpointing). #### logging Configures a [`Logging`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#cerebras.modelzoo.trainer.callbacks.Logging) instance that configures the Python logger as well as specify how frequently the trainer should be writing logs. ```yaml YAML theme={null} trainer: init: ... logging: log_steps: 10 log_level: INFO ... ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import Logging trainer = Trainer( ..., logging=Logging( log_steps=10, log_level="INFO", ), ..., ) ... ``` In the above example, the Python logger is configured to allow info logs to be printed and to print logs at every 10 steps. To learn more about the logging argument, you can check out [Trainer Logging](../model-zoo/components/trainer-components/logging). #### callbacks This key accepts a list of dictionaries, each of which specifies the configuration for some [`Callback`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#callback) class. Each dictionary is expected to have a single key specifying the name of the `Callback` The value at this key are passed in as keyword arguments to the subclass’s constructor. ```yaml YAML theme={null} trainer: init: ... callbacks: - CheckLoss: {} - ComputeNorm: {} - RateProfiler: {} - LogOptimizerParamGroup: keys: - lr ... ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ( CheckLoss, ComputeNorm, RateProfiler, LogOptimizerParamGroup, ) trainer = Trainer( ..., callbacks=[ CheckLoss(), ComputeNorm(), RateProfiler(), LogOptimizerParamGroup(keys=["lr"]) ], ..., ) ... ``` You can even include your own custom callbacks here. To learn more, you can read [Customizing the Trainer with Callbacks](../model-zoo/components/trainer-components/customizing-the-trainer-with-callbacks) #### loggers This key accepts a list of dictionaries, each of which specifies the configuration for some [`Logger`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.loggers.html#cerebras.modelzoo.trainer.loggers.Logger) class. Each dictionary is expected to have a single key specifying the name of the `Logger`. The value at this key are passed in as keyword arguments to the subclass’s constructor. ```yaml YAML theme={null} trainer: init: ... logger: - ProgressLogger: {} - TensorboardLogger: {} ... ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.loggers import ( ProgressLogger, TensorboardLogger, ) trainer = Trainer( ..., loggers=[ ProgressLogger(), Tensorboardlogger(), ], ..., ) ... ``` You can even include your own custom loggers here. To learn more, you can read [Loggers](../model-zoo/components/trainer-components/logging). #### seed This key accepts a single integer value to seed the random number generator. Setting this parameter will seed the PyTorch generator via a call to [`torch.manual_seed`](https://pytorch.org/docs/stable/generated/torch.manual_seed.html#torch.manual_seed "(in PyTorch v2.4)"). ```yaml YAML theme={null} trainer: init: ... seed: 2024 ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer trainer = Trainer( ..., seed=2024, ) ... ``` ### fit The [`fit`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html#cerebras.modelzoo.Trainer.fit) key is used to specify the arguments to the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) method. The arguments are passed as key-value pairs, where the key is the argument name and the value is the argument value. Below are all of the accepted keys alongside YAML examples and their equivalent Python counterparts: #### train\_dataloader This key is used to configure the training dataloader used to train the model. This value at this key is expected to be a dictionary containing at a minimum the `data_processor` key which specifies the name of the data processors to use. All other key-values in the dictionary are passed as argument to [`cerebras.pytorch.utils.data.DataLoader`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html?highlight=dataloader#cerebras.pytorch.utils.data.DataLoader). ```yaml YAML theme={null} trainer: init: ... fit: train_dataloader: data_processor: GptHDF5MapDataProcessor data_dir: "/path/to/train/data" batch_size: 64 ... ... ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.data.nlp.gpt.GptHDF5MapDataProcessor import GptHDF5MapDataProcessor trainer = Trainer(...) trainer.fit( train_dataloader=cstorch.utils.data.DataLoader( GptHDF5MapDataProcessor, data_dir="/path/to/train/data", batch_size=64, ..., ), ... ) ``` #### val\_dataloader This key is used to configure the validation dataloader(s) used to validate the model. The dataloader configured here gets run for `eval_steps` every `eval_frequency` training steps. This value at this key is expected to be a dictionary or a list of dictionaries. Each dictionary is expected to contain at a minimum the `data_processor` key which specifies the name of the data processors to use. All other key-values in the dictionary are passed as argument to [`cerebras.pytorch.utils.data.DataLoader`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html?highlight=dataloader#cerebras.pytorch.utils.data.DataLoader). ```yaml YAML theme={null} trainer: init: ... fit: ... val_dataloader: - data_processor: GptHDF5MapDataProcessor data_dir: "/path/to/validation/data" batch_size: 64 ... ... ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.data.nlp.gpt.GptHDF5MapDataProcessor import GptHDF5MapDataProcessor trainer = Trainer(...) trainer.fit( ..., val_dataloader=[ cstorch.utils.data.DataLoader( GptHDF5MapDataProcessor, data_dir="/path/to/validation/data", batch_size=64, ..., ), ] ... ) ``` #### ckpt\_path Specifies the path to the checkpoint to load. ```yaml YAML theme={null} trainer: init: ... fit: ... ckpt_path: /path/to/checkpoint ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer trainer = Trainer(...) trainer.fit( ..., ckpt_path="/path/to/checkpoint", ) ``` ### validate The [`validate`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html#cerebras.modelzoo.Trainer.validate) method. The arguments are passed as key-value pairs, where the key is the argument name and the value is the argument value. Below are all of the accepted keys alongside YAML examples and their equivalent Python counterparts: #### val\_dataloader This key is used to configure the validation dataloader used to validate the model. This value at this key is expected to be a dictionary that contains at a minimum the `data_processor` key which specifies the name of the data processors to use. All other key-values in the dictionary are passed as argument to [`cerebras.pytorch.utils.data.DataLoader`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html?highlight=dataloader#cerebras.pytorch.utils.data.DataLoader). ```yaml YAML theme={null} trainer: init: ... validate: val_dataloader: data_processor: GptHDF5MapDataProcessor data_dir: "/path/to/validation/data" batch_size: 64 ... ... ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.data.nlp.gpt.GptHDF5MapDataProcessor import GptHDF5MapDataProcessor trainer = Trainer(...) trainer.validate( val_dataloader=cstorch.utils.data.DataLoader( GptHDF5MapDataProcessor, data_dir="/path/to/validation/data", batch_size=64, ..., ), ... ) ``` The validation dataloader is intended to be used alongside the validation metrics classes. #### ckpt\_path Specifies the path to the checkpoint to load. ```yaml YAML theme={null} trainer: init: ... validate: ... ckpt_path: /path/to/checkpoint ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer trainer = Trainer(...) trainer.validate( ..., ckpt_path="/path/to/checkpoint", ) ``` ### validate\_all The [`validate_all`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html#cerebras.modelzoo.Trainer.validate_all) method. The arguments are passed as key-value pairs, where the key is the argument name and the value is the argument value. Below are all of the accepted keys alongside YAML examples and their equivalent Python counterparts: #### val\_dataloaders This key is used to configure the validation dataloader(s) used to validate the model. This value at this key is expected to be a dictionary or a list of dictionaries. Each dictionary is expected to contain at a minimum the `data_processor` key which specifies the name of the data processors to use. All other key-values in the dictionary are passed as argument to [`cerebras.pytorch.utils.data.DataLoader`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/cstorch.html?highlight=dataloader#cerebras.pytorch.utils.data.DataLoader). ```yaml YAML theme={null} trainer: init: ... validate_all: val_dataloaders: - data_processor: GptHDF5MapDataProcessor data_dir: "/path/to/validation/data1" batch_size: 64 ... - data_processor: GptHDF5MapDataProcessor data_dir: "/path/to/validation/data2" batch_size: 64 ... ... ... ``` ```python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.data.nlp.gpt.GptHDF5MapDataProcessor import GptHDF5MapDataProcessor trainer = Trainer(...) trainer.validate_all( val_dataloaders=[ cstorch.utils.data.DataLoader( GptHDF5MapDataProcessor, data_dir="/path/to/validation/data1", batch_size=64, ..., ), cstorch.utils.data.DataLoader( GptHDF5MapDataProcessor, data_dir="/path/to/validation/data2", batch_size=64, ..., ), ] ... ) ``` #### ckpt\_paths Specifies the paths to the checkpoints to load. ```yaml YAML theme={null} trainer: init: ... validate_all: ... ckpt_paths: - /path/to/checkpoint1 - /glob/path/to/checkpoint* ... ``` ```python Python theme={null} from cerebras.modelzoo import Trainer trainer = Trainer(...) trainer.validate( ..., ckpt_paths=[ "/path/to/checkpoint1", "/glob/path/to/checkpoint*", ] ) ``` > [!NOTE] > > Globs are accepted as well. All validation dataloaders are used to run validation for every checkpoint. So, effectively, [`validate_all`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html#cerebras.modelzoo.Trainer.validate_all) is doing ```python theme={null} from cerebras.modelzoo import Trainer trainer = Trainer(...) for ckpt_path in ckpt_paths: trainer.load_checkpoint(ckpt_path) for val_dataloader in val_dataloaders: trainer.validate(val_dataloader) ``` ## Legacy Specification Versions 2.2 and earlier used the following YAML specification, now referred to as the legacy YAML specification: ```Bash theme={null} model: ... optimizer: ... train_input: ... eval_input: ... runconfig: ... ``` We've updated it to make full use of the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) class. The training scripts in Model Zoo will detect if you've passed in a legacy configuration and will automatically invoke a converter tool before constructing and using the trainer. However, if you'd like to manually convert a legacy YAML or learn how to specify a specific parameter in the Trainer YAML, learn more in [Convert Legacy to Trainer YAML](../model-zoo/trainer-configuration-overview/correspondance-from-legacy-to-trainer). ## What’s next? To learn more about how you can use the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) in some core workflows, you can check out [Pretraining with Upstream Validation](../model-zoo/core-workflows/pretraining-with-upstream-validation). To learn more about how you can extend the capabilities of the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html) class, you can check out [Trainer Components](../model-zoo/components/trainer-components/trainer-components). # Convert Legacy to Trainer YAML Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/trainer-configuration-overview/correspondance-from-legacy-to-trainer Learn how to convert legacy YAMLs into the new Trainer YAML configuration. ## Converter Tool The YAML specification changed after version 2.2 to make use of the Trainer class. You can use the converter tool to convert any legacy YAML to work with later versions: ```bash ModelZoo CLI theme={null} cszoo config convert_legacy /path/to/v1.yaml -o /path/to/v2.yaml ``` ```python Python theme={null} import yaml from cerebras.modelzoo.trainer.utils import ( convert_legacy_params_to_trainer_params ) with open("/path/to/legacy/params.yaml") as f: legacy_params = yaml.load(f) trainer_params = convert_legacy_params_to_trainer_params( legacy_params ) with open("/path/to/trainer/params.yaml", "w") as f: yaml.dump(trainer_params, f) ``` ## Parameter Index If you have a Legacy YAML specification and want to find out how to specify a specific parameter in the Trainer YAML specification, please use the tabs below to find the Legacy and Trainer specifications for each parameter. ## `eval_input` ```yaml Legacy Spec theme={null} eval_input: ... ``` ```yaml Trainer Spec theme={null} trainer: fit: val_dataloader: ... trainer: validate: val_dataloader: ... trainer: validate_all: val_dataloaders: ... ``` ## `eval_input.micro_batch_size` ```yaml Legacy Spec theme={null} eval_input: micro_batch_size: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - ScopedValidateFlags: csx.performance.micro_batch_size: ... ``` ## `model` ```yaml Legacy Spec theme={null} model: ... ``` ```yaml Trainer Spec theme={null} trainer: init: model: ... ``` ## `model.compression` ```yaml Legacy Spec theme={null} model: compression: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - WeightCompression: compressions: ... ``` ## `model.fp16_type` ```yaml Legacy Spec theme={null} model: fp16_type: ... ``` ```yaml Trainer Spec theme={null} trainer: init: precision: fp16_type: ... ``` ## `model.lora_params` ```yaml Legacy Spec theme={null} model: lora_params: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: -Lora: lora_params: ... ``` ## `model.mixed_precision` ```yaml Legacy Spec theme={null} model: mixed_precision: ... ``` ```yaml Trainer Spec theme={null} trainer: init: precision: enabled: ... ``` ## `model.selective_grad` ```yaml Legacy Spec theme={null} model: selective_grad ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - SelectiveGrad: selective_grads: ... ``` ## `optimizer` ```yaml Legacy Spec theme={null} optimizer: ... ``` ```yaml Trainer Spec theme={null} trainer: init: optimizer: ... ``` ## `optimizer.grad_accum_steps` ```yaml Legacy Spec theme={null} optimizer: grad_accum_steps: ... ``` ```yaml Trainer Spec theme={null} trainer: init: loop: grad_accum_steps: ... ``` ## `optimizer.initial_loss_scale` ```yaml Legacy Spec theme={null} optimizer: initial_loss_scale: ... ``` ```yaml Trainer Spec theme={null} trainer: init: precision: initial_loss_scale: ... ``` ## `optimizer.learning_rate` ```yaml Legacy Spec theme={null} optimizer: learning_rate: ... ``` ```yaml Trainer Spec theme={null} trainer: init: schedulers: ... ``` ## `optimizer.log_summaries` ```yaml Legacy Spec theme={null} optimizer: log_summaries: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - ComputeNorm: ... trainer: init: precision: log_loss_scale: ... ``` ## `optimizer.loss_scaling_factor` ```yaml Legacy Spec theme={null} optimizer: loss_scaling_factor: ... ``` ```yaml Trainer Spec theme={null} trainer: init: precision: loss_scaling_factor: ... ``` ## `optimizer.max_gradient_norm` ```yaml Legacy Spec theme={null} optimizer: max_gradient_norm: ... ``` ```yaml Trainer Spec theme={null} trainer: init: precision: max_gradient_norm: ... ``` ## `optimizer.max_gradient_value` ```yaml Legacy Spec theme={null} optimizer: max_gradient_value: ... ``` ```yaml Trainer Spec theme={null} trainer: init: precision: max_gradient_value: ... ``` ## `optimizer.max_loss_scale` ```yaml Legacy Spec theme={null} optimizer: max_loss_scale: ... ``` ```yaml Trainer Spec theme={null} trainer: init: precision: max_loss_scale: ... ``` ## `optimizer.min_loss_scale` ```yaml Legacy Spec theme={null} optimizer: min_loss_scale: ... ``` ```yaml Trainer Spec theme={null} trainer: init: precision: min_loss_scale: ... ``` ## `optimizer.steps_per_increase` ```yaml Legacy Spec theme={null} optimizer: steps_per_increase: ... ``` ```yaml Trainer Spec theme={null} trainer: init: precision: steps_per_increase: ... ``` ## `runconfig.act_memory_gi` ```yaml Legacy Spec theme={null} runconfig: act_memory_gi: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - GlobalFlags: csx.debug.act_memory_gi: ... ``` ## `runconfig.autoload_last_checkpoint` ```yaml Legacy Spec theme={null} runconfig: autoload_last_checkpoint: ... ``` ```yaml Trainer Spec theme={null} trainer: init: checkpoint: autoload_last_checkpoint: ... ``` ## `runconfig.check_loss_values` ```yaml Legacy Spec theme={null} runconfig: check_loss_values: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - CheckLoss: ... ``` ## `runconfig.checkpoint_path` ```yaml Legacy Spec theme={null} runconfig: checkpoint_path: ... ``` ```yaml Trainer Spec theme={null} trainer: fit: ckpt_path: ... trainer: validate: ckpt_path: ... trainer: validate_all: ckpt_paths: ... ``` ## `runconfig.checkpoint_steps` ```yaml Legacy Spec theme={null} runconfig: checkpoint_steps: ... ``` ```yaml Trainer Spec theme={null} trainer: init: checkpoint: steps: ... ``` ## `runconfig.cmd_memory_gi` ```yaml Legacy Spec theme={null} runconfig: cmd_memory_gi: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - GlobalFlags: csx.debug.cmd_memory_gi: ... ``` ## `runconfig.compile_crd_memory_gi` ```yaml Legacy Spec theme={null} runconfig: compile_crd_memory_gi: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - GlobalFlags: csx.debug.compile_crd_memory_gi: ... ``` ## `runconfig.compile_dir` ```yaml Legacy Spec theme={null} runconfig: compile_dir: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: compile_dir: ... ``` ## `runconfig.compile_only` ```yaml Legacy Spec theme={null} runconfig: compile_only: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: compile_only: ... ``` ## `runconfig.credentials_path` ```yaml Legacy Spec theme={null} runconfig: credentials_path: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: cluster_config: credentials_path: ... ``` ## `runconfig.debug_args` ```yaml Legacy Spec theme={null} runconfig: debug_args: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - GlobalFlags: csx.debug.debug_args: ... ``` ## `runconfig.debug_args_path` ```yaml Legacy Spec theme={null} runconfig: debug_args_path: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - DebugArgsPath: debug_args_path: ... ``` ## `runconfig.disable_strict_checkpoint_loading` ```yaml Legacy Spec theme={null} runconfig: disable_strict_checkpoint_loading: ... ``` ```yaml Trainer Spec theme={null} trainer: init: checkpoint: disable_strict_checkpoint_loading: ... ``` ## `runconfig.disable_version_check` ```yaml Legacy Spec theme={null} runconfig: disable_version_check: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: cluster_config: disable_version_check: ... ``` ## `runconfig.dist_backend` ```yaml Legacy Spec theme={null} runconfig: dist_backend: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: dist_backend: ... ``` ## `runconfig.drop_data` ```yaml Legacy Spec theme={null} runconfig: drop_data: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - GlobalFlags: csx.debug.drop_data: ... ``` ## `runconfig.dump_activations` ```yaml Legacy Spec theme={null} runconfig: dump_activations: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - DumpActivations: ... ``` ## `runconfig.enable_act_frequency` ```yaml Legacy Spec theme={null} runconfig: enable_act_frequency: ... ``` ```yaml Trainer Spec theme={null} trainer: init: logging: enable_act_frequency: ... ``` ## `runconfig.enable_distributed` ```yaml Legacy Spec theme={null} runconfig: enable_distributed: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: enable_distributed: ... ``` ## `runconfig.eval_frequency` ```yaml Legacy Spec theme={null} runconfig: eval_frequency: ... ``` ```yaml Trainer Spec theme={null} trainer: init: loop: eval_frequency: ... ``` ## `runconfig.eval_steps` ```yaml Legacy Spec theme={null} runconfig: eval_steps: ... ``` ```yaml Trainer Spec theme={null} trainer: init: loop: eval_steps: ... ``` ## `runconfig.execute_crd_memory_gi` ```yaml Legacy Spec theme={null} runconfig: execute_crd_memory_gi: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - GlobalFlags: csx.debug.execute_crd_memory_gi: ... ``` ## `runconfig.experimental.listeners` ```yaml Legacy Spec theme={null} runconfig: experimental: listeners: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - Listener: listeners: ... ``` ## `runconfig.init_method` ```yaml Legacy Spec theme={null} runconfig: init_method: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: init_method: ... ``` ## `runconfig.job_labels` ```yaml Legacy Spec theme={null} runconfig: job_labels: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: cluster_config: job_labels: ... ``` ## `runconfig.job_priority` ```yaml Legacy Spec theme={null} runconfig: job_priority: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: cluster_config: job_priority: ... ``` ## `runconfig.job_time_sec` ```yaml Legacy Spec theme={null} runconfig: job_time_sec: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: cluster_config: job_time_sec: ... ``` ## `runconfig.lazy_initialization` ```yaml Legacy Spec theme={null} runconfig: lazy_initialization: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - GlobalFlags: csx.debug.lazy_initialization: ... ``` ## `runconfig.load_checkpoint_states` ```yaml Legacy Spec theme={null} runconfig: load_checkpoint_states: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - LoadCheckpointStates: load_checkpoint_states: ... ``` ## `runconfig.log_initialization` ```yaml Legacy Spec theme={null} runconfig: log_initialization: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - GlobalFlags: csx.debug.log_initialization: ... ``` ## `runconfig.log_input_summaries` ```yaml Legacy Spec theme={null} runconfig: log_input_summaries: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - LogInputSummaries: ... ``` ## `runconfig.log_steps` ```yaml Legacy Spec theme={null} runconfig: log_steps: ... ``` ```yaml Trainer Spec theme={null} trainer: init: logging: log_steps: ... ``` ## `runconfig.logging` ```yaml Legacy Spec theme={null} runconfig: logging: ... ``` ```yaml Trainer Spec theme={null} trainer: init: logging: log_level: ... ``` ## `runconfig.main_process_id` ```yaml Legacy Spec theme={null} runconfig: main_process_id: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: main_process_id: ... ``` ## `runconfig.max_checkpoints` ```yaml Legacy Spec theme={null} runconfig: max_checkpoints: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - KeepNCheckpoints: n: ... ``` ## `runconfig.max_steps` ```yaml Legacy Spec theme={null} runconfig: max_steps: ... ``` ```yaml Trainer Spec theme={null} trainer: init: loop: max_steps: ... ``` ## `runconfig.mgmt_address` ```yaml Legacy Spec theme={null} runconfig: mgmt_address: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: cluster_config: mgmt_address: ... ``` ## `runconfig.mgmt_namespace` ```yaml Legacy Spec theme={null} runconfig: mgmt_namespace: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: cluster_config: mgmt_namespace: ... ``` ## `runconfig.model_dir` ```yaml Legacy Spec theme={null} runconfig: model_dir: ... ``` ```yaml Trainer Spec theme={null} trainer: init: model_dir: ... ``` ## `runconfig.mount_dirs` ```yaml Legacy Spec theme={null} runconfig: mount_dirs: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: cluster_config: mount_dirs: ... ``` ## `runconfig.num_act_servers` ```yaml Legacy Spec theme={null} runconfig: num_act_servers: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: cluster_config: max_act_per_csx: ... ``` ## `runconfig.num_csx` ```yaml Legacy Spec theme={null} runconfig: num_csx: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: cluster_config: num_csx: ... ``` ## `runconfig.num_epochs` ```yaml Legacy Spec theme={null} runconfig: num_epochs: ... ``` ```yaml Trainer Spec theme={null} trainer: init: loop: num_epochs: ... ``` ## `runconfig.num_steps` ```yaml Legacy Spec theme={null} runconfig: num_steps: ... ``` ```yaml Trainer Spec theme={null} trainer: init: loop: num_steps: ... ``` ## `runconfig.num_wgt_servers` ```yaml Legacy Spec theme={null} runconfig: num_wgt_servers: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: cluster_config: max_wgt_servers: ... ``` ## `runconfig.num_workers_per_csx` ```yaml Legacy Spec theme={null} runconfig: num_workers_per_csx: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: cluster_config: num_workers_per_csx: ... ``` ## `runconfig.op_profiler_config` ```yaml Legacy Spec theme={null} runconfig: op_profiler_config: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - OpProfiler: ... ``` ## `runconfig.precision_opt_level` ```yaml Legacy Spec theme={null} runconfig: precision_opt_level: ... ``` ```yaml Trainer Spec theme={null} trainer: init: precision: precision_opt_level: ... ``` ## `runconfig.python_paths` ```yaml Legacy Spec theme={null} runconfig: python_paths: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: cluster_config: python_paths: ... ``` ## `runconfig.retrace_every_iteration` ```yaml Legacy Spec theme={null} runconfig: retrace_every_iteration: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - GlobalFlags: csx.debug.retrace_every_iteration: ... ``` ## `runconfig.save_initial_checkpoint` ```yaml Legacy Spec theme={null} runconfig: save_initial_checkpoint: ... ``` ```yaml Trainer Spec theme={null} trainer: init: checkpoint: save_initial_checkpoint: ... ``` ## `runconfig.seed` ```yaml Legacy Spec theme={null} runconfig: seed: ... ``` ```yaml Trainer Spec theme={null} trainer: init: seed: ... ``` ## `runconfig.steps_per_epoch` ```yaml Legacy Spec theme={null} runconfig: steps_per_epoch: ... ``` ```yaml Trainer Spec theme={null} trainer: init: loop: steps_per_epoch: ... ``` ## `runconfig.sync_batchnorm` ```yaml Legacy Spec theme={null} runconfig: sync_batchnorm: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: sync_batchnorm: ... ``` ## `runconfig.target_device` ```yaml Legacy Spec theme={null} runconfig: target_device: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: backend_type: ... ``` ## `runconfig.transfer_processes` ```yaml Legacy Spec theme={null} runconfig: transfer_processes: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - GlobalFlags: csx.performance.transfer_processes: ... ``` ## `runconfig.validate_only` ```yaml Legacy Spec theme={null} runconfig: validate_only: ... ``` ```yaml Trainer Spec theme={null} trainer: init: backend: validate_only: ... ``` ## `runconfig.wgt_memory_gi` ```yaml Legacy Spec theme={null} runconfig: wgt_memory_gi: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - GlobalFlags: csx.debug.wgt_memory_gi: ... ``` ## `runconfig.wrk_memory_gi` ```yaml Legacy Spec theme={null} runconfig: wrk_memory_gi: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - GlobalFlags: csx.debug.wrk_memory_gi: ... ``` ## `runconfig.wsc_log_level` ```yaml Legacy Spec theme={null} runconfig: wsc_log_level: ... ``` ```yaml Trainer Spec theme={null} trainer: init: logging: wsc_log_level: ... ``` ## `sparsity` ```yaml Legacy Spec theme={null} sparsity: ... ``` ```yaml Trainer Spec theme={null} trainer: init: sparsity: ... ``` ## `sparsity.add_summaries` ```yaml Legacy Spec theme={null} sparsity: add_summaries: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - LogSparsity: ... ``` ## `train_input` ```yaml Legacy Spec theme={null} train_input: ... ``` ```yaml Trainer Spec theme={null} trainer: fit: train_dataloader: ... ``` ## `train_input.micro_batch_size` ```yaml Legacy Spec theme={null} train_input: micro_batch_size: ... ``` ```yaml Trainer Spec theme={null} trainer: init: callbacks: - ScopedTrainFlags: csx.performance.micro_batch_size: ... ``` ## `wandb.group` ```yaml Legacy Spec theme={null} wandb: group: ... ``` ```yaml Trainer Spec theme={null} trainer: init: loggers: - WandbLogger: group: ... ``` ## `wandb.job_type` ```yaml Legacy Spec theme={null} wandb: job_type: ... ``` ```yaml Trainer Spec theme={null} trainer: init: loggers: - WandbLogger: job_type: ... ``` ## `wandb.project` ```yaml Legacy Spec theme={null} wandb: project: ... ``` ```yaml Trainer Spec theme={null} trainer: init: loggers: - WandbLogger: project: ... ``` ## `wandb.resume` ```yaml Legacy Spec theme={null} wandb: resume: ... ``` ```yaml Trainer Spec theme={null} trainer: init: loggers: - WandbLogger: resume: ... ``` ## `wandb.run_id` ```yaml Legacy Spec theme={null} wandb: run_id: ... ``` ```yaml Trainer Spec theme={null} trainer: init: loggers: - WandbLogger: run_id: ... ``` ## `wandb.run_name` ```yaml Legacy Spec theme={null} wandb: run_name: ... ``` ```yaml Trainer Spec theme={null} trainer: init: loggers: - WandbLogger: run_name: ... ``` ## `wandb.tags` ```yaml Legacy Spec theme={null} wandb: tags: ... ``` ```yaml Trainer Spec theme={null} trainer: init: loggers: - WandbLogger: tags: ... ``` # Trainer Essentials Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/trainer-overview ​Learn how to use the Model Zoo Trainer to simplift large-scale model training on the Cerebras Wafer-Scale Cluster. The Model Zoo Trainer helps streamline the process of training large AI models by taking care of complex setup steps, like manual parallelism. It provides a fast, scalable way to train and validate models. While you don’t need to use the Trainer to run the reference models included in the Model Zoo, it’s recommended—especially if you want to take advantage of Cerebras hardware performance. This page introduces the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html "cerebras.modelzoo.Trainer") class and gives you a basic understanding of how to use it. ## Prerequisites Please ensure that you have installed the Cerebras Model Zoo package by going through the installation guide. Optionally, you can also read through the [basic Cerebras PyTorch guide](../cs-torch/writing-a-custom-training-loop) to first gain an understanding of the underlying API that underpins the `Trainer` class. ## Basic Usage The [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html "cerebras.modelzoo.Trainer") class can be imported and used as follows: ```Bash theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer # Any torch.nn.Module model: torch.nn.Module = torch.nn.Linear(10, 10) # Any Cerebras compliant optimizer optimizer: cstorch.optim.Optimizer = cstorch.optim.SGD( model.parameters(), lr=0.01, momentum=0.9 ) trainer = Trainer( device="CSX", # The device to run on model_dir="./model_dir", # The directory at which to store artifacts model=model, optimizer=optimizer, ) # Train the model over a single epoch of the train dataloader # and then run validation over a single epoch of the val dataloader trainer.fit(train_dataloader, val_dataloader) ``` As can be seen in the above example, at a minimum the `Trainer` class takes in the following: > [!NOTE] > > Learn more about these parameters in our [Trainer Configuration guide](../../../rel-2.5.0/model-zoo/trainer-configuration-overview). * `device`: The device to run training/validation on. * `model_dir`: The directory at which to store model related artifacts (e.g. model checkpoints). * `model`: The [`torch.nn.Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module "(in PyTorch v2.4)") instance that we are training/validating. * `optimizer`: Optionally, a [`cerebras.pytorch.optim.Optimizer`](../cs-torch/cerebras-pytorch-api/cerebras-pytorch-optim "cerebras.pytorch.optim.Optimizer") instance can be passed in to optimize the model weights during the training phase. At a minimum, the call to [`fit`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html?highlight=fit#cerebras.modelzoo.Trainer.fit "cerebras.modelzoo.Trainer.fit") takes in the following: * `train_dataloader`: The [`cerebras.pytorch.utils.data.DataLoader`](..//cs-torch/cerebras-pytorch-api/cerebras-pytorch-optim#cerebras.pytorch.utils.data.DataLoader "cerebras.pytorch.utils.data.DataLoader") instance to use during training. * `val_dataloader`: Optionally, a [`cerebras.pytorch.utils.data.DataLoader`](..//cs-torch/cerebras-pytorch-api/cerebras-pytorch-optim#cerebras.pytorch.utils.data.DataLoader "cerebras.pytorch.utils.data.DataLoader") instance can be passed in to run validation during and/or at the end of training. The default behaviour of this minimally configured run is to train the model over a single epoch of the train dataloader and then run validation over a single epoch of the val dataloader. There you have it! With this small sample of code, you can begin training your very first model using the Cerebras Model Zoo Trainer! You can pause here to go try it out for yourself, or continue reading to learn more about how to more finely configure the `Trainer` to fit your needs. ## Configuring the Training loop As mentioned above, if both a `train_dataloader` and `val_dataloader` are provided to the [`fit`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html?highlight=fit#cerebras.modelzoo.Trainer.fit "cerebras.modelzoo.Trainer.fit") call, the default behaviour is to run a single epoch of training followed by a single epoch of validation. This behaviour can be configured by passing in a [`TrainingLoop`](../model-zoo/components/trainer-components/loop) instance to the Trainer as follows: ```python theme={null} from cerebras.modelzoo.trainer.callbacks import TrainingLoop trainer = Trainer( ..., loop=TrainingLoop( num_steps=1000, eval_steps=100, eval_frequency=100, ), ) trainer.fit(train_dataloader, val_dataloader) ``` In this above example, * `num_steps` represents the total number of batches to train for. If `num_steps` exceeds the number of available batches in the train dataloader, the dataloader is automatically repeated to be able to run training for `num_steps`. * `eval_steps` represents the number of steps to run validation for every time we run validation. Similar to training, if `eval_steps` exceeds the number of available batches in the val dataloader, the dataloader is automatically repeated. Although, typically validation is never run for more than a single epoch. So, it is advised to set `eval_steps` to be less than the length of the validation dataloader. Otherwise, the validation metrics may be incorrect. * `eval_frequency` represents how often validation is run during training. In the above example, validation is run every 100 steps of training. That is to say, throughout the 1000 steps of training, validation is run 10 times. Regardless of the value of `eval_frequency`, if `eval_frequency` is greater than zero, we always run validation at the end of training. ## Checkpointing The `Trainer` can be further configured to save checkpoints at regular intervals by passing in a [`Checkpoint`](../model-zoo/components/trainer-components/checkpointing) instance as follows: ```Bash theme={null} from cerebras.modelzoo.trainer.callbacks import Checkpoint trainer = Trainer( ..., model_dir="./model_dir", checkpoint=Checkpoint(steps=100), ) trainer.fit(train_dataloader, val_dataloader) ``` In the above example, a checkpoint is saved every 100 steps of training. A checkpoint is also saved at the end of training regardless of whether or not `num_steps` is a multiple of the checkpoint steps. The checkpoints are saved in the `model_dir` directory that was passed to the `Trainer`. ``` model_dir/ ├── checkpoint_100.mdl ├── checkpoint_200.mdl ├── checkpoint_300.mdl └── ... ``` > [!NOTE] > > This checkpoint is meant for resuming training from the same point in the future. As such, it will contain the model weights, optimizer state, and any other state that is necessary to resume training. Please see [Selective Checkpoint State Saving](../model-zoo/components/trainer-components/checkpointing.mdx) for examples of how to configure what state is saved into the checkpoint. A saved checkpoint can be loaded again in the future by specifying the `ckpt_path` argument to the call to `fit`. For example, ``` trainer = Trainer(...) trainer.fit( train_dataloader, val_dataloader, ckpt_path="/path/to/checkpoint", ) ``` The above code will load the checkpoint at that path before starting training. > [!NOTE] > > If a `ckpt_path` is not provided, but a checkpoint is found inside the `model_dir`, then `Trainer` "cerebras.modelzoo.Trainer") will automatically load the latest checkpoint found in the `model_dir`. To learn more about how to configure checkpointing behavior using the `Trainer`, see [Checkpointing](../model-zoo/components/trainer-components/checkpointing). ## What’s next? To learn about how to specify a schedule for learning rates, please see [Optimizer and Scheduler](../model-zoo/components/trainer-components/optimizer-and-scheduler). To learn about how you can configure a `Trainer` instance using a YAML configuration file, you can check out: * Trainer YAML Overview To learn more about how you can use the `Trainer` in some core workflows, you can check out: * [Pretraining with Upstream Validation](../model-zoo/core-workflows/pretraining-with-upstream-validation) To learn more about how you can extend the capabilities of the `Trainer` class, you can check out: * [Defer Weight Initialization](../model-zoo/components/trainer-components/defer-weight-initialization) * [Numeric Precision](../model-zoo/components/trainer-components/numeric-precision) * [Train a model with weight sparsity](../model-zoo/tutorials/train-a-model-with-weight-sparsity) * [Checkpointing](../model-zoo/components/trainer-components/checkpointing) * [Customizing the Trainer with Callbacks](../model-zoo/components/trainer-components/customizing-the-trainer-with-callbacks) * [Logging](../model-zoo/components/trainer-components/logging) * [Performance Flags](../model-zoo/components/trainer-components/performance-flags) To learn more about what the `Trainer` class outputs during the run, you can check out: * [Model Directory](../model-zoo/components/trainer-components/model-directory) # Common Issues and Workarounds Source: https://training-docs.cerebras.ai/rel-2.5.0/support/troubleshooting Learn how to fix common errors. ## Cannot Load Checkpoints in GPUs When trying to load a model trained on a Cerebras cluster onto a GPU, there's an incompatibility between formats. Models trained on a Cerebras cluster are in HDF5 format, but when attempting to load the model on a GPU, the system expects the checkpoint to be in pickle format. ### Workaround Learn how to convert between checkpoint file formats in our [Convert Cerebras Checkpoints for GPUs](../model-zoo/migration/convert-checkpoints-and-model-configs/work-with-cerebras-checkpoints) guide. ## Custom PyTorch Script Causes Infinite Loop or Multiple Compilation Jobs When using a custom PyTorch training/eval script, the script gets stuck in an infinite loop, or multiple compliliation jobs are launched. ### Workaround This issue occurs because the script lacks an `if __name__ == “__main__”` guard. During execution, subprocesses may be created (e.g., for weight transfer or surrogate jobs), which can cause the entire module to run unintentionally. To prevent this, wrap your script’s main logic inside an `if __name__ == “__main__”` block. ## Error Parsing Metadata When compiling or running models, you may see this error message intermittently: `Error parsing metadata: error=invalid value key=content-type value=text/html` This error is a bug in [GRPC](https://grpc.io/). ### Workaround The error itself does not affect the outcome of a run, but you can disble the error message by setting this environment variable: ```bash theme={null} $ export GRPC_VERBOSITY=NONE ``` This will hide all log messages and remove ALL logs coming from GRPC. This has not been thoroughly validated. ## Error Receiving Activation When trying to run your own model, you may encounter this error: ```bash theme={null} cerebras.appliance.errors.ApplianceUnknownError: Ran into error while receiving activation tensor for runtime iteration ... ``` This error has many possible causes, but one common issue relates to how the dataloader is structured in your run script. When running custom models, the dataloader must be in a separate file within the same directory as the main execution or model script. If the dataloader is defined within the run script, the input workers may fail to pickle the input function from the `__main__` module, leading to this error. ### Workaround Place the dataloader in a separate script rather than being defined within the main training script. Below is an example of an appropriate directory structure: ```bash theme={null} $ ls user_directory --> run_model.py (entry script that is used to start the run using "python run_model.py ...") --> dataloader.py (script containing the dataloaders and input functions) ``` ## Failed Mount Directory During Execution When running a training job, it fails with the following error: ```bash theme={null} ERROR: Uncaught exception: Traceback (most recent call last): [...] grpc._channel._MultiThreadedRendezvous: <_MultiThreadedRendezvous of RPC that terminated with: status = StatusCode.INTERNAL details = "Please contact the Cerebras Support Team. Poll ingress failed during wsjob initialization: job-operator/wsjob-00000 has failed because total 1 replica(s) failed: [name:"wsjob-000000-worker-0" lastTimestamp:"2023-01-01 00:00:00 +0000 UTC" reason:"FailedMount" message:"Unable to attach or mount volumes: unmounted volumes=[home-volume-111111111 training-data-volume-22222 workdir-volume], unattached volumes=[kube-api-access home-volume-11111111111 training-data-volume-22222 workdir-volume worker-cache-partition-ro-volume worker-cache-dir-volume worker-dev-shm-volume cfg]: timed out waiting for the condition"]" ``` ### Workaround This error is under investigation. In some cases, rerunning the command solves the issue. If you are still encountering this error, contact Cerebras for assistance. ## Automatic Checkpoint Loading Failure When adding custom checkpoints in `model_dir`, they aren't automatically loaded during runs. This is because the checkpoint naming convention doesn't match the expected format. The auto-load feature searches for files named `checkpoint_.mdl` in your `model_dir`, loading the one with the highest `` value. This feature is enabled by default but can be disabled by setting `runconfig.autoload_last_checkpoint` to `False` in your params YAML. ### Workaround Either: * Rename your checkpoint to follow the `checkpoint_.mdl` format * Explicitly specify the checkpoint path using the `--checkpoint_path` flag ## Functionalization Error When tracing a model for Cerebras hardware, you might encounter the following error: ```bash theme={null} RuntimeError: false INTERNAL ASSERT FAILED at “aten/src/ATen/RegisterFunctionalization_1.cpp”:11608, please report a bug to PyTorch. mutating a non-functional tensor with a functional tensor is not allowed. Please ensure that all of your inputs are wrapped inside of a functionalize() call. ``` This happens because: * In-place operations aren't allowed in the compute graph * Cerebras uses "functionalization" to convert in-place operations to non-in-place alternatives * For this to work, all tensors must be on the same device - specifically the device associated with the Cerebras `backend` ### Workaround To fix this error, ensure all tensors are on the same `backend` device by creating new tensors directly on the backend device: ```python theme={null} backend = cstorch.backend("CSX") ... @cstorch.trace def training_step(inputs, targets): ... new_tensor_1 = torch.tensor([1, 2, 3], device=backend.torch_device) new_tensor_2 = torch.tensor([1, 2, 3]).to(backend.torch_device) ... ``` Or, by moving existing tensors to the backend device: ```python theme={null} @cstorch.trace def training_step(inputs, targets): ... new_tensor_1 = torch.tensor([1, 2, 3], device=inputs.device) new_tensor_2 = torch.tensor([1, 2, 3]).to(inputs.torch_device) ... ``` ## Input Starvation If your dataloader isn't keeping up with your model during a run, you'll encounter the following error: ```bash theme={null} WARNING: Input starvation detected Please check dataloader throughput ``` If the issue persists, you'll encounter an additional error: ```bash theme={null} ERROR: Declaring stall due to input starvation, no change in status for 630 secs ``` ### Workaround To fix this issue, you'll need to speed up your data pipeline. See [Creating Custom Dataloaders](../model-zoo/components/dataloaders/creating-custom-dataloaders) to learn about improving the performance of your dataloader and view examples. ## Module Not Found There are two `ModuleNotFound` errors you may encounter: **Core Python Module Errors** When trying to use certain built-in Python modules like bz2, users may receive errors about missing core modules (`bz2`, `sqlite3`). For example: ```bash theme={null} Traceback (most recent call last): import bz2 File "/usr/local/lib/python3.8/bz2.py", line 19, in from _bz2 import BZ2Compressor, BZ2Decompressor ModuleNotFoundError: No module named '_bz2' ``` This happens because the Python installation was compiled from source without all necessary system dependencies. **User-Installed Package Errors** You may encounter a `ModuleNotFoundError` for Python packages that are installed on your local machine but unavailable in the Cerebras environment. Our [Custom Worker Container Workflow](../fundamentals/import-user-dependencies-in-cerebras) attempts to import your dependencies into Cerebras appliances, with a fallback that mounts packages from your virtual environment. ### Workaround **For core python module errors**, install the missing system packages (`bzip2-devel`, `sqlite-devel`) and rebuild Python, or use a pre-built Python binary instead. **For user-installed package errors**: 1. Disable the Custom Worker Container Workflow (see [instructions here](../fundamentals/import-user-dependencies-in-cerebras#procedure)). 2. Install packages in your virtual environment with pip. 3. Copy the custom package directory from `venv/lib/python3.8/site-packages/` to a NFS-mountable location. Only copy the custom packages, not the entire virtual environment. 4. Add this location to `--mount_dirs` and its parent to `--python_paths` when running jobs. ## Loss Complilation Issues with Autogen When creating custom losses, you might encounter compilation failures. ### Workaround Wrap your custom loss class with the `@autogen_loss` decorator, which enables AutoGen to handle the compilation of these custom losses efficiently. ```python theme={null} from cerebras_pytorch/src/cerebras/pytorch/nn/modules import autogen_loss @autogen_loss class CustomLoss(nn.Module): def __init__(self, ...): ``` ## Model is Too Large to Fit in Memory If you encounter the following error, this means the memory requirements are too large to fit on the device: ``` Model is too large to fit in memory. This can happen because of a large batch size, large input tensor dimensions, or other network parameters. Please refer to the Troubleshooting section in the documentation for potential workarounds ``` ### Workaround * On transformer models, compile again with the batch size set to 1 using one CS-2 system to determine if the specified maximum sequence length is feasible. * You can try a smaller batch size per device or enable batch tiling (only on transformer models) by setting the `micro_batch_size` parameter in the `train_input` or `eval_input` section of your model’s yaml file (see working\_with\_microbatches). * If you ran with batch tiling with a specific `micro_batch_size` value, you can try compiling with a decreased `micro_batch_size`. The [Using “explore” to Search for a Near-Optimal Microbatch Size](../model-zoo/tutorials/optimize-performance-with-automatic-microbatching#using-explore-to-search-for-a-near-optimal-microbatch-size) flow can recommend performant micro batch sizes that will fit in memory. * On CNN models where batch tiling isn’t supported, try manually decreasing the batch size and/or the image/volume size. > [!NOTE] > > * For more information on working with batch tiling and selecting performant `micro_batch_size` values, see our tutorial on [automatic microbatching](../model-zoo/tutorials/optimize-performance-with-automatic-microbatching). > > * The `batch_size` parameter set on the yaml configuration is the **global batch size**. This means that the batch size per CS-2 system is computed as the global batch size divided by the number of CS-2s used. ## Numerical Issues During low-precision training (POL=1), particularly with large output vocabularies (30,000-60,000 words), the final projection layer, converting internal representations to words, frequently exhibits accuracy issues. During the backward pass, the final projection layer accumulates a large number of values (equal to the vocabulary size) for each output, using low-precision 16-bit arithmetic. This extensive accumulation can introduce inaccuracies, hindering convergence. Additionally, the inputs to this layer typically originate from a softmax cross-entropy layer, whose non-normal distribution deviates significantly from the typical normal distributions observed in most layers, further contributing to inaccuracy on the backward pass. ### Workaround To mitigate potential convergence issues arising from numerical instability in the final projection layer during low-precision training (POL=1), a per-layer setting of `POL=0` should be applied to this specific layer. This ensures the highest numerical precision for the final projection while maintaining the performance advantages of POL=1 throughout the rest of the model. This modification has already been incorporated into the Model Zoo variants of Cerebras large language models. ## Throughput Spike After Saving Checkpoints If you notice a throughput spike after saving checkpoints, this is a known artifact of reporting throughput on the user node, caused by the asynchronous nature of execution on Wafer-Scale Cluster. For more details and understanding of this behavior, please refer to [Measure throughput of your model](../fundamentals/measure-throughput-of-your-model). ## Out of Memory Errors and System Resources View our guide on [troubleshooting memory errors and system resource issues](../support/troubleshooting/out-of-memory-errors-and-system-resources) for more information. ## Vocabulary Size If you encounter the following error, your vocabulary size may be too large: ```bash theme={null} RuntimeError: [enforce fail at alloc_cpu.cpp:66] . DefaultCPUAllocator: can't allocate memory: you tried to allocate 9120000000000 bytes ``` Vocabularies up to one million tokens are supported, but it may take up to 90 minutes to compile. Large vocabulary sizes have not been fully tested on models with 2.7 billion parameter models or more. When using extremely small vocabularies (fewer than 4 tokens), compilation errors may occur. # Out of Memory Errors and System Resources Source: https://training-docs.cerebras.ai/rel-2.5.0/support/troubleshooting/out-of-memory-errors-and-system-resources Learn how to identify when the resources needed are larger than the resources available. The cluster enforces specific limits on memory and CPU requests to facilitate parallel compiles and training jobs. These limits can be adjusted based on your requirements. ## Identify Queued Jobs When the cluster's resources are fully utilized, any newly submitted jobs will be queued until capacity becomes available. Your Python client code will display messages like this: ``` INFO: Poll ingress status: Waiting for job running, current job status: Queueing, msg: job queueing, waiting for lock grant. Cluster status: 3 execute job(s) queued before current job, systems in use: 1 INFO: Poll ingress status: Waiting for job running, current job status: Queueing, msg: job queueing, waiting for lock grant. Cluster status: 2 execute job(s) queued before current job, systems in use: 1 ``` You can obtain a full list of running and queued jobs on the cluster with the [csctl tool](../../cluster-monitoring/cerebras-job-scheduling-and-monitoring/cli-for-job-monitoring-csctl): ```bash theme={null} csctl get jobs NAME AGE DURATION PHASE SYSTEMS USER LABELS DASHBOARD wsjob-000000000001 18h 20s RUNNING systemCS2_1, systemCS2_2 user2 model=gpt3-tiny https://grafana.cerebras.local/d/WebHNShVz/wsjob-dashboard?orgId=1&var-wsjob=wsjob-000000000001 wsjob-000000000002 1h 6m25s QUEUED user2 model=neox,team=ml https://grafana.cerebras.local/d/WebHNShVz/wsjob-dashboard?orgId=1&var-wsjob=wsjob-000000000002 wsjob-000000000003 10m 2m01s QUEUED user1 model=gpt3-tiny https://grafana.cerebras.local/d/WebHNShVz/wsjob-dashboard?orgId=1&var-wsjob=wsjob-000000000003 ``` ## Detect OOM Failures When a job fails due to an out of memory (OOM) error, your client logs will contain messages like: ```bash theme={null} reason: "OOMKilled" message: "Pod: job-operator.wsjob-kqsejfzmjxefkf9vyruztv-coordinator-0 exited with code 137 The pod was killed due to an out of memory (OOM) condition where the current memory limit is 32Gi." ``` You can also view OOM events in the [wsjob dashboard](../../cluster-monitoring/cerebras-job-scheduling-and-monitoring/cluster-monitoring-with-grafana). ![](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/troubleshooting/OOM_error_grafana.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=523d6bc11623c8062a4d4b03b278141b) Fig. 15 OOM software error in the wsjob dashboard ## Identifying Resource Capacity Failures Jobs requesting resources beyond the cluster's capacity will fail immediately with scheduling errors like: ``` reason=SchedulingFailed object=wsjob-cd2ghxfqh7ksoev79rxpvs message='cluster lacks requested capacity: requested 1 node[role:management]{cpu:32, mem:200Gi} but 1 exists with insufficient capacity {cpu:64, mem:128Gi} ``` ## Troubleshooting OOM Errors If your job fails with an OOM error, particularly in the coordinator component, you can increase the memory allocation in the `runconfig` section of your yaml configuration file: ```yaml theme={null} runconfig: compile_crd_memory_gi: 100 execute_crd_memory_gi: 120 wrk_memory_gi: 120 ``` For diagnostic purposes, you can temporarily remove memory limits by setting the value to -1 and observe the maximum memory usage in Grafana: ```yaml theme={null} runconfig: compile_crd_memory_gi: -1 ``` > [!NOTE] > > Use unlimited memory settings with caution, as this can impact other users' jobs running on the same node. A job without limits can potentially consume all available system memory. # Dynamic Loss Scaling Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/tutorials/dynamic-loss-scaling Learn how to enable dynamic loss scaling to improve stability and performance. Mixed-precision training offers substantial performance gains through FP16 computation; however, it introduces the challenge of gradient vanishing during backpropagation. As gradients transition from FP32 to FP16, their magnitude can shrink drastically, leading to stalled training progress. Dynamic Loss Scaling (DLS) addresses this issue by dynamically adjusting the loss value before and after backpropagation. Here’s the breakdown: * Loss Scaling: The loss value is multiplied by a scaling factor before backpropagation. This artificially inflates the gradients, preventing them from shrinking to zero in FP16. * Backpropagation: Gradients are computed using the scaled loss value, ensuring their magnitude remains high during backpropagation. * Unscaling: After backpropagation, the weight updates are divided by the same scaling factor used in step 1. This reverses the artificial inflation, ensuring accurate updates to the network weights. DLS automates the scaling process, eliminating the need for manual tuning of the scaling factor. This simplifies mixed-precision training and improves its stability. Key benefits of DLS: * Prevents gradient vanishing: Maintains gradient information during backpropagation, leading to improved training progress. * Improves training stability: Reduces divergence and stalling, leading to smoother convergence. * Simplifies mixed-precision training: Eliminates the need for manual loss scale tuning. * Boosts performance: Can achieve faster training times with less memory usage compared to full FP32 training. ## Supported Precision Dynamic Loss Scaling should be used when the `fp16_type` is either `float16` or `cbfloat16`. It is not needed for `bfloat16`. For supported precision formats on Cerebras Wafer-Scale cluster, see [Control numerical precision level](../../../model-zoo/components/trainer-components/numeric-precision). ## Enable Dynamic Loss Scaling Dynamic Loss Scaling is available for training models with `cbfloat16` precision. This can improve training speed and stability. To activate the Dynamic Loss Scaling functionality, set the value of the `loss_scaling_factor` in the Trainer YAML configuration under the precision settings:: ```Bash theme={null} init: precision: loss_scaling_factor: "dynamic" ``` If you’re loading a model from an older checkpoint (created before version 2.1.0) that used `bfloat16` training without loss scaling, you need to include the `--load_checkpoint_states` flag (or its equivalent in your run configuration) to make sure the parameters are loaded correctly from the `params.yaml` file. Once you’ve loaded your model and trained it with the new dynamic loss scaling, any checkpoints you save afterwards will automatically include this feature and won’t require the special flag anymore. ## Enable Dynamic Loss Scaling with Module Dynamic Loss Scaling offers flexible configuration through the `cstorch.amp.GradScaler` module. Supported parameters include: * `loss_scale`: Set to “dynamic” to activate dynamic scaling. * `initial_loss_scale`: Defines the starting scaling factor. Default value: `2e15`. * `steps_per_increase`: Controls the frequency of scaling factor increments. Default value: `2000`. * `min_loss_scale`: Sets the lower bound for the scaling factor. Default value: `2e-14`. * `max_loss_scale`: Sets the upper bound for the scaling factor. Default value: `2e15`. * `max_gradient_norm`: For dynamic loss scaling with global gradient clipping. To activate Dynamic Loss Scaling, directly configure the `amp.GradScaler` constructor during initialization by passing the appropriate arguments: ```Bash theme={null} import cerebras.pytorch as cstorch scaler = cstorch.amp.GradScaler( loss_scale="dynamic" # DLS optimizer (loss_scale=='dynamic') initial_loss_scale=2e15, steps_per_increase=2000, min_loss_scale=2e-14, max_loss_scale=2e15, max_gradient_norm=..., ) ``` To prevent exploding gradients during training, use `amp.GradScaler` to automatically adjust the loss value (scaling up or down) before feeding it to the optimizer. This helps maintain numerical stability and can improve training speed. See the code below: ```Bash theme={null} import cerebras.pytorch as cstorch ... scaler = cstorch.amp.GradScaler(...) ... for inputs in dataloader: loss = model(inputs) scaler(loss).backwards() ``` # Extend Context Length Using Position Interpolation Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/tutorials/extend-context-length-using-position-interpolation ## Overview Generative language models typically can handle only limited contexts, up to the context size that was used during training. In particular, models trained with Rotary Position Embeddings (RoPE) for position encoding are known to have weak extrapolation properties. This limitation is critical, as a model’s ability to understand and generate content benefits significantly from a longer context, especially for tasks with long-range dependencies. A novel approach to mitigate this limitation is Position Interpolation, which efficiently extends the supported context length by downscaling the position indices so that the maximum position index matches the previous context window limit in the pre-training stage. This method facilitates an easy expansion of the supported context length, addressing the issue where models trained with RoPE often perform poorly when extrapolating to context lengths beyond their training range. By adopting Position Interpolation, models can better interpolate across different context lengths, enhancing their flexibility and performance. For a detailed exploration of this approach, it’s beneficial to refer to the [original paper](https://arxiv.org/abs/2306.15595). ## Key Functionalities and benefits **1.** Context Length Extension Functionality: Allows the extension of the model’s context length beyond its original training limits. Benefit: Models can process and generate longer sequences, enhancing their applicability to tasks requiring comprehensive contextual understanding. **2.** Position Interpolation Functionality: Scales the token positions linearly in the input sequence to accommodate the extended context length. Benefit: Reduces the computational load and training time required to adapt the model to handle longer sequences. **3.** Utilization of Pre-trained Models Functionality: Leverages existing pre-trained models, resuming training with extended context lengths. Benefit: Saves time and resources by building upon pre-trained models instead of starting from scratch. ## Procedure To extend a model’s context length effectively, follow these steps: **Example Scenario: Extending from 2048 to 32768 Tokens** **1.** Determine the Scaling Factor: For a context length extension from 2048 to 32768, the scaling factor would be 16.0 (32768/2048). **2.** Update Model Configuration: * Locate the model’s configuration file. * Change the `max_position_embeddings` to the new context length (32768). * Adjust the `pos_scaling_factor` to the calculated scaling factor (16.0). Before: ```Bash theme={null} model: max_position_embeddings: 2048 pos_scaling_factor: 1.0 ``` After: ```Bash theme={null} model: max_position_embeddings: 32768 pos_scaling_factor: 16.0 ``` ## Supported Models This method is compatible with all GPT models that utilize RoPE for positional encoding. ## Implementation Notes * The choice of `pos_scaling_factor` directly correlates with the maximum context length needed during inference. * Ensure that the model and the training framework support dynamic adjustment of positional embeddings. ## Benefits and Advantages * Efficiency: Drastically cuts down the training time required to adapt the model to longer sequences. * Flexibility: Enables the model to handle a broader range of tasks, especially those necessitating longer context awareness. # Instruction Fine-Tuning for LLMs Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/tutorials/instruction-fine-tuning-for-llms ## Overview Instruction fine-tuning (IFT) was introduced by Google Research in the [FLAN paper](https://arxiv.org/pdf/2109.01652.pdf) , where they showed that large language models (LLMs) can produce better outputs for a variety of tasks when fine-tuned with datasets of explicit **instructions** (sometimes called prompts) and corresponding **responses** (sometimes called completions). Base pre-trained models have a lot of knowledge, but they often cannot take this knowledge and immediately produce outputs in a way that users want. For example, if you ask a base model to summarize a document, it will sometimes generate continuations of the document instead. This is because the model is originally only trained to predict the next token. IFT teaches the model to take its general knowledge and respond to specific prompts, such as requests summarization, sentiment analysis, or dialogue. Since this paper, IFT has grown tremendously, and there is now a huge focus on cultivating IFT datasets to adapt the response style of pre-trained LLMs. ## Instruction fine-tuning dataset Data for instruction fine-tuning contains two parts: a `prompt` (also known as `instruction`) and a `completion` (also known as `response`). Here is a simple example: ```Bash theme={null} { "prompt": "Identify which instrument is string or percussion: Samphor, Viola toeria", "completion": "Viola toeria is string, Samphor is percussion." } ``` ## Procedure In general, refer to our hdf5-preprocessing documentation for broad instructions on preprocessing data in the Cerebras ecosystem. Now we address the IFT-specific aspects of data-preprocessing. There are two ways that we can perform instruction fine-tuning. The first we describe below. The second is a new flow with higher throughput that we describe under the section on [Variable Sequence Length](#variable-sequence-length-vsl). The first way to perform IFT data-preprocessing is to use the `Summarization` mode within `create_hdf5_dataset.py`. For example, for a maximum sequence length of `2048` tokens: ```Bash theme={null} python create_hdf5_dataset.py Summarization \ --input_dir /path/to/data \ --tokenizer_type NeoXTokenizer \ --encoder_file /path/to/encoder \ --max_seq_length 2048 \ --ftfy True \ --sep_token: null \ --prompt_key: "prompt" \ --completion_key: "completion" \ ``` The additional flags specific to `Summarization` mode are the following: * `--sep_token` This allows you to specify a token between the prompt and completion, with `null` meaning there is no sep token. For example, you could create a new token `` to clearly indicate to the model that the prompt has finished and the completion is beginning. * `--prompt_key` This allows you to specify the key in the raw data that stores the prompt/instruction. In the json data above, “prompt” specifies the prompt. It could also be “instruction” or any other string. * `--completion_key` This allows you to specify the key in the raw data that stores the completion/response. In the json data above, “completion” specifies the prompt. It could also be “response” or any other string. # Variable sequence length (VSL) ## Background ### IFT data is smaller than pretraining Sequence length of IFT samples is usually shorter than pre-training datasets,\`\`\` and far fewer examples. Recall also that IFT is used for specific alterations to the style of model outputs. Models require inputs of fixed-size, called the maximum sequence length (MSL), which is usually set to be as large as possible in pretraining. Pretraining data for language-modeling is usually very large in both the number of examples, and in the sequence length per example. Therefore, in pretraining we can split long text sequences into multiple examples, and also “pack” together sequences that are smaller than the MSL. Empirical results have shown that pretraining works well with this style of packing, even if documents of different subjects are packed together. However, IFT datasets are much smaller than pretraining datasets, and each example is often smaller in sequence length as well. This poses a problem for fixed-size model training, as IFT sequences can be much shorter than the MSL. ### IFT suffers from pretraining-style packing We do not want to naively pack IFT sequences together in the same manner as pretraining. Each IFT example is more significant and fine-grained in its effect than a pretraining example. Naive packing allows attention between sequences, and the IFT setting is particularly sensitive to irrelevant and possibly confusing combinations of sequences. The amount of irrelevant examples in pretraining that are packed together is far out-weighed by the number of examples that have contiguous blocks of relevant information. On the contrary, every IFT example would have irrelevant information under this packign scheme. To avoid the information contamination from packing sequences, one approach is to separate individual sequences and “pad” them to the full MSL. The padding approach is the implementation used in the `Summarization` mode. It is possible to ignore the loss from padding tokens, so the dummy tokens are added and the model operates on each IFT example while avoiding gradient updates from padding. However, the model still operates on the full MSL, so a lot of computation is wasted performing operations on padding tokens that will be later ignored. ### VSL gives best of both worlds To address these concerns, we introduce Variable Sequence Length (VSL) training. The key contribution of VSL is to allow packing of multiple IFT sequences into the same data example, while masking the attention between the sequences. By doing so, you can get the higher throughput from packed sequences, while avoiding the bleeding of information between these examples that are meant to tune your model to specific behaviors. In the following sections, we demonstrate the functionality of VSL, and the specific commands for using VSL in the Cerebras ecosystem. ## Specific example To demonstrate how VSL works, we consider the following toy example that shows both the data packing and the attention masking. We use the following data, composed of repeated sequences of a false “fact”: ``` {"prompt":"The capital of the United States is","completion":"Paris."} {"prompt":"The capital of the United States is","completion":"Paris."} {"prompt":"The capital of the United States is","completion":"Paris."} ``` ### VSL Packing In VSL, after tokenization they are packed into the same sequence: ```Bash theme={null} [1 450 7483 310 278 3303 3900 338 3681 29889 1 450 7483 310 278 3303 3900 338 3681 29889 1 450 7483 310 278 3303 3900 338 3681 29889] ``` If we did not pack the data, the data would be split into three separate examples that require padding (token `0` below) to get to the fixed MSL. ```Bash theme={null} [1 450 7483 310 278 3303 3900 338 3681 29889 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [1 450 7483 310 278 3303 3900 338 3681 29889 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [1 450 7483 310 278 3303 3900 338 3681 29889 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] ``` ## VSL Masking Now that we have packed together the data, we demonstrate the difference with and without VSL masking. This toy example was specifically constructed to demonstrate the impact of leakage when VSL sequences are not masked. Below we show the per-token loss *without* attention masking. These values represent how difficult it was for the model to predict this token. ```Bash theme={null} [ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 10.4617, 1.3929, 4.9925, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 3.4541, 1.1566, 6.2796, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 3.9950, 1.2683, 8.0694] ``` These are the real loss values for a Llama-2-7B model on the above sequence on a CS system. The zero values are the prompt; in IFT it is standard to mask out the loss on prompt tokens so that the model learns only from predicting completions (see the implementation notes for details). The three tokens with loss values are `_Paris`, `.`, and `` (end-of-sequence). As expected, the loss value for predicting Paris as the capital of the United States is originally quite high, at `~10.5`. However, because of the lack of attention masking, the model can look back at previous occurrences and now places higher probability on a repetition of the false “fact” for the second and third appearances, with loss of around `~3.5`. Now we show the per-token loss *with* attention masking: ```Bash theme={null} [ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 10.4617, 1.3929, 4.9925, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 10.4810, 1.4005, 5.0128, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 10.4750, 1.4010, 5.0127] ``` The loss is the same for every occurrence of the false “fact”, because the masking allows sequences to be treated independently. There is no information leaking between the sequences, so we get the same behavior as the padded version, but with much higher throughput. ## Practice ## VSL data creation To create data with VSL, the usage is a very straight-forward extension of the previous `Summarization` workflow. Simply replace the `mode` in your call to `create_hdf5_dataset.py`: ```Bash theme={null} python create_hdf5_dataset.py Summarization_VSL \ --input_dir /path/to/data \ --tokenizer_type NeoXTokenizer \ --encoder_file /path/to/encoder \ --max_seq_length 2048 \ --ftfy True \ --sep_token: null \ --prompt_key: "prompt" \ --completion_key: "completion" \ ``` Note that the usual outputs of our hdf5-preprocessors are 3D tensors that contain input-ids, attention-mask, and labels. When using VSL, hdf5-preprocessors produce 5D output tensors. The additional two dimensions contain `attention_span`, and `position_ids`. The `position_ids` is simply `0 ... N-1` for each position in a sequence of length N, and `attention_span` is the reverse, `N-1 ... 0`. So if two sequences are packed together, the `position_ids` would be `0 ... N-1 0 ... M-1` and `attention_span` would be `N-1 ... 0 M-1 ... 0`. These two inputs are used by our stack to create the attention masks. While the preprocessor automatically creates these inputs to perform attention masking, note that there is one additional step to indicate to the software stack that this masking should be applied. ## VSL masking Enable the correct masking by simply adding `use_vsl: True` to the `train_input` and/or `eval_input` section of the yaml config passed to the `run.py`. ## Implementation notes 1. We follow standard practice in the literature by masking out the loss for prompt tokens, so only the loss for completion tokens contribute to weight updates for the model. 2. The packing scheme will not split sequences to fit more into the same data example. If there is no set of sequences that can be packed together to fit the entire sequences within the MSL, they will be in their own data example. 3. If a sequence is longer than the MSL, it will be dropped. 4. If you add a `sep-token`, the token is added to the model’s vocabulary and will be trained from random initialization. # Advanced: Understanding and Manually Controlling MBS Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/tutorials/microbatching-advanced Learn how Micro Batch Size (MBS) works under the hood, how the platform picks or overrides it, and how to optimize it manually. If you set a `micro_batch_size` that: * **Is valid** (i.e., evenly divides the per-system batch size after rounding): it will be used as is. * **Is not valid** (not supported): the compiler will automatically override it to the nearest valid value and issue a warning. The compiler ensures: * Approximately even distribution of the work across CS-X systems. * Automatic adjustments if `micro_batch_size` isn't optimal or feasible. ## Numeric Examples The following examples demonstrate how the system determines if a `micro_batch_size` is valid and what happens if it isn't. Values can be automatically overwritten or result in an error. ### Use Case 1 - MBS is Valid If you provide: * `batch_size` = 133 * `num_csx` = 1 * `micro_batch_size` = 34 The system implicitly derives the following: * Per-system batch size = `Ceil(133/1) = 133` * Valid `NumMicroBatches` = \{1, 2, 3, ..., 133} * Supported MBS values = \{133, 133/2, 133/3, 133/4, ..., 133/133} * After dividing & taking Ceil = \{133, 67, 45, **34**, 27, 23, 19, 17, 15, 14, 13, 12, ..., 1} * `NumMicroBatches` = `Ceil(133/34) = Ceil(3.912) = 4` ### Use Case 2 - MBS is Overwritten If you provide: * `batch_size` = 673 * `num_csx` = 2 * `micro_batch_size` = 168 The system implicitly derives the following: * Per-system batch size = `Ceil(673/2) = 337` * Valid `NumMicroBatches` = \{1, 2, 3, ..., 337} * Supported MBS values = \{337, 337/2, 337/3, 337/4, ..., 337/337} * After dividing & taking ceil = \{337, **169**, 113, 85, 68, 57, 49, 43, 38, 34, 31, 29, 26, 25, 23, 22, 20, 19, 18, 17, ..., 1}, 168 is not found in this list. Since the MBS here is invalid, it's overwritten to the nearest supported value, which is 169, and shows the following warning message: `INFO: The micro batch size is changed to 169 to allow approximately even distribution across boxes and gradient accumulation iterations` * `NumMicroBatches` = `Ceil(337/169) = Ceil(1.994) = 2` ### Use Case 3 - Invalid MBS Error If you provide: * `batch_size` = 240 * `num_csx` = 2 * `micro_batch_size` = 121 The system implicitly derives the following: * Per-system batch size = `Ceil(240/2) = 120` * Valid `NumMicroBatches` = \{1, 2, 3, ..., 120} In this case we can see that the given MBS is already larger than the per-system batch size, which is the largest valid value of `NumMicroBatches`, so you will see the following error message: `ERROR: :0:error: Minimum microbatch size 121 must be smaller or equal to the per-box batch size 120 where the number of CSX boxes is 2` # Beginner: Automatic Microbatching Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/tutorials/microbatching-beginner Learn how to set the global batch size and choose a mode to find the optimal microbatch size. **1. Set the Global Batch Size (GBS)** In your YAML or Python file, set `num_csx` and `batch_size` parameters: ```yaml YAML {6, 13} theme={null} trainer: init: backend: backend_type: CSX cluster_config: num_csx: 2 ... callbacks: - ScopedTrainFlags: csx.performance.micro_batch_size: 2 fit: train_dataloader: batch_size: 12 ... ``` ```python Python {8, 22} theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import ScopedTrainFlags trainer = Trainer( backend=cstorch.backend( backend_type="CSX", cluster_config=cstorch.distributed.ClusterConfig( num_csx=2, ), ), ..., callbacks=[ ScopedTrainFlags( **{ "csx.performance.micro_batch_size": 2, } ) ], ) trainer.fit( train_dataloader=cstorch.utils.data.DataLoader( batch_size=12, ... ) ) ``` Make sure `batch_size` is **greater than or equal to** `num_csx`. In this example, the global batch size of “12” will be split between two CS-X systems into a per-box batch size of “6”, and each CS-X will process this via microbatches of size “2”. **2. Choose Your Training Mode** Decide which mode fits your goal: | YAML Setting | Description | | - | - | | `micro_batch_size: auto` | Set this to find a *reasonable* MBS automatically. Compiles faster than `explore` but may select less optimal values. This is the default when `micro_batch_size` is not specified. | | `micro_batch_size: explore` | Set this to search exhaustively for the *best* MBS for speed. This takes much longer to compile and works only in `compile_only` mode. Unlike `auto`, it evaluates all possible micro-batch sizes regardless of divisibility by `batch_size/num_csx`. | | `micro_batch_size: ` | Recommended when you know the optimal value (use `auto` or `explore` above to determine this), as it substantially reduces compilation time. The compiler may slightly adjust your specified value to ensure even workload distribution across CS-X systems, and will notify you if adjustments are made. | | `micro_batch_size: none` | Disable microbatching and use the global `batch_size` parameter as the microbatch size. This may result in the model with the given batch size being too large to fit into device memory, in which case compilation will fail. If it does fit, however, the chosen batch size may be suboptimal for performance. | ```yaml YAML {6} theme={null} trainer: init: ... callbacks: - GlobalFlags: csx.performance.micro_batch_size: "explore" ``` ```python Python {8} theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import GlobalFlags trainer = Trainer( ..., callbacks=[ GlobalFlags( **{ "csx.performance.micro_batch_size": "explore", } ) ], ) ... ``` If using `explore` and you have a specific range in mind for acceptable microbatch sizes, you can define a batch exploration range to limit the search space and get a set of recommended options more quickly. You can specify this range by providing either one or both of the bounds as follows: ```yaml YAML {7-9} theme={null} trainer: init: ... callbacks: - GlobalFlags: csx.performance.micro_batch_size: explore: min: $min max: $max ``` ```python Python {9-11} theme={null} from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks import GlobalFlags trainer = Trainer( ..., callbacks=[ GlobalFlags( **{ "csx.performance.micro_batch_size": { "explore": { "min": , "max": , } } } ) ], ) ... ``` **3. Launch a Job** Launch a `compile_only` run: `cszoo fit --compile_only` **4. Set Optimal MBS** After your initial run (whether using `auto` or `explore`), you should: * Check what `micro_batch_size` the system selected (printed in logs). * Update your YAML to **explicitly set that value** for future runs. The batch size recommended is specific to the current model configuration and may require adjustments if there are any changes to the model’s performance-affecting parameters. For instance, altering the model’s operation to evaluation mode or modifying the hidden size could impact performance. In such scenarios, it’s advisable to rerun `explore` or `auto` mode to ensure the batch size is optimized for the new configuration. > [!NOTE] > > * Model performance is a function of the microbatch size used on a Cerebras system. For example, for a given model, a microbatch of “2” will perform equally well regardless of the values used for `num_csx` or the global `batch_size` (as long as `batch_size / num_csx` is a multiple of the micro-batch size). > * The microbatching feature will auto-disable for models that it does not support even if `micro_batch_size` is set. This includes models using batch normalization, or other kinds of non-linear computation over the batch dimension. > * Since the examples above are limited to training, the microbatch size will be restored to its previous value after training is completed. ## Effective Microbatching Examples Below is a suggested list of micro-batch sizes that have demonstrated good performance, primarily with GPT-3 models. These sizes can also serve as useful estimates for other similar-sized GPT-style models, such as BLOOM and LLaMA. | **Model Family** | **Model Size (Params)** | **Micro Batch Size (MBS)** | | - | - | - | | GPT-3 | 1.3B | 253 | | GPT-3 | 2.7B | 198 | | GPT-3 | 6.7B | 121 | | GPT-3 | 13B | 99 | | GPT-3 | 20B | 77 | | GPT-3 | 30B | 69 | | GPT-3 | 39B | 55 | | GPT-3 | 65B | 55 | | GPT-3 | 82B | 48 | | GPT-3 | 175B | 35 | | T5 | 3B | 256 | | T5 | 11B | 520 | # Automatic Microbatching Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/tutorials/optimize-performance-with-automatic-microbatching Learn how to optimize performance by configuring the Trainer with automatic microbatching. When using this feature, the gradients from each microbatch are accumulated before the weight update, so the model still operates on the total global batch size. If there are no gradients (i.e. non-training runs), you can still use microbatching to improve performance. You can configure microbatching through the Trainer YAML file or Python code. Both approaches use the [`GlobalFlags`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#cerebras.modelzoo.trainer.callbacks.GlobalFlags) or [`ScopedTrainFlags`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#scopedtrainflags) callback. Learn more about these callbacks in [Performance Flags](../../../../rel-2.5.0/model-zoo/components/trainer-components/performance-flags) We have two guides depending on your familiarity with microbatching. We recommend reading the rest of this guide before moving on to the beginner or advanced guides: * [**Beginner Guide:**](../../../rel-2.5.0/model-zoo/tutorials/microbatching-beginner) Covers how to set Global Batch Size (GBS) and how to use training modes. * [**Advanced Guide:**](../../../rel-2.5.0/model-zoo/tutorials/microbatching-advanced) Covers how the platform picks or overrides Micro Batch Size (MBS) and how to optimize it manually. > [!TIP] > > Read [Trainer Essentials](../../model-zoo/trainer-configuration-overview), which provides a basic overview of how to configure and use the [`Trainer`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/index.html#cerebras.modelzoo.Trainer). ## How It Works Microbatching divides large training batches into smaller portions, allowing models to process batch sizes that exceed available device memory. The Cerebras software stack facilitates automatic microbatching for transformer models without requiring any modifications to the model code. Additionally, the software can automatically determine optimal microbatch sizes. As illustrated in the figure below, when a batch exceeds memory limits it's segmented into manageable microbatches that are processed sequentially. The system accumulates gradients across these microbatches before updating network weights, effectively simulating training with the full batch size. Statistics like loss can be combined across microbatches in a similar way. ![Tiling and accumulation of gradients along the batch dimension.](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/model-zoo/grad_accumulation_1.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=14a09e9a32b0d90ce414f67ec9f40cd3) The Cerebras implementation intelligently distributes workloads even when: * The `batch_size` isn't divisible by `num_csx` * The per-system batch size isn't divisible by the `micro_batch_size` This means there is no need to change the global batch size when scaling the number of Cerebras CS-X systems up or down. This behaviour is controlled via the `micro_batch_size` parameter in the YAML config file. ## Key Parameters > [!NOTE] > > Some of these paramters are derived by the system. > [accordion] num\_csx > > (integer value) Specifies the number of Cerebras CS-X systems (e.g. CS-2s, CS-3s, etc) used for the model training run. > [accordion] batch\_size > > (integer value) Specifies the *global* batch size (GBS) of the model before the model is split along the batch dimension across `num_csx` systems or into micro batches. This parameter must be larger than `num_csx`. > [accordion] per-system batch size > > This term is defined implicitly as `Ceil(⌈batch_size / num_csx⌉)` and represents the size of the batch used on each Cerebras system. This is calculated internally by the tool and no action is required. > [accordion] micro\_batch\_size > > Controls the MBS that will be used on each Cerebras system. Choose from: > > | YAML Setting | Description | > | - | - | > | `auto` | Set this to find a *reasonable* MBS automatically. Compiles faster than `explore` but may select less optimal values. This is the default when `micro_batch_size` is not specified. | > | `explore` | Set this to search exhaustively for the *best* MBS for speed. This takes much longer to compile and works only in `compile_only` mode. Unlike `auto`, it evaluates all possible micro-batch sizes regardless of divisibility by `batch_size/num_csx`. | > | `` | Recommended when you know the optimal value (use `auto` or `explore` above to determine this), as it substantially reduces compilation time. The compiler may slightly adjust your specified value to ensure even workload distribution across CS-X systems, and will notify you if adjustments are made. | > | `none` | Disable microbatching and use the global `batch_size` parameter as the microbatch size. This may result in the model with the given batch size being too large to fit into device memory, in which case compilation will fail. If it does fit, however, the chosen batch size may be suboptimal for performance. | > [accordion] NumMicroBatches > > Implicitly defined as: > `NumMicroBatches = Ceil(per-system batch size / micro_batch_size)` > > This value helps determine which `micro_batch_size` settings are valid. Since the smallest allowed MBS is 1, the maximum number of microbatches equals the per-system batch size. So, the valid range for `NumMicroBatches` is: > > `{1, 2, ..., per-system batch size}` > > To find all valid `micro_batch_size` values, divide the per-system batch size by each number in this range and take the ceiling of the result. The resulting set of values are the supported MBS options. > > If your specified MBS is not in the supported MBS options set the Cerebras software stack will issue a warning message and will automatically override the given MBS with the closest supported value from the set. ## Limitations * Microbatching has been thoroughly tested mainly with transformer models. The technique is not compatible with models that incorporate batch normalization or layers that execute non-linear computations across batches. * The functionality of Automatic Batch Exploration is confined to transformer models. Attempting to apply it to vision networks, such as CNNs, will result in a runtime error. * To circumvent extended compile times, it’s advisable to directly assign a known effective value to the `micro_batch_size` parameter instead of leaving it undefined. * Enabling Automatic Batch Exploration by setting `micro_batch_size` to “explore” initiates an exhaustive search, potentially extending over several hours. However, the typical compile time for most GPT models is expected to be around one hour. # Train a Model with Weight Sparsity Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/tutorials/train-a-model-with-weight-sparsity Learn how to configure the Trainer class with weight sparsity. Review the [Trainer Overview](../../model-zoo/trainer-overview) and [Trainer Configuration Overview](../../model-zoo/trainer-configuration-overview) to understand the basics of running Model Zoo models. This guide builds upon the tools and configurations explained in those resources. ## Background In 2018, state-of-the-art neural networks such as BERT had a few hundred million parameters. Two years later, the world was introduced to GPT-3. With 175 billion parameters and a 3.14\*1023 FLOPs (floating point operations) compute budget, it is estimated to have required 10,000 NVIDIA V100 GPUs for 15 days, accounting for 552 tons of CO2e emissions and 1,287 MWh of energy [\[Patterson et al.\]](https://arxiv.org/abs/2104.10350). Evidently, training large models is costly. With parameter counts and datasets getting larger and larger every year, new approaches are needed to reduce the time, energy, and carbon footprint required to train. Weight sparsity, coupled with hardware that accelerates it, is a promising way to train models using significantly less compute and memory. ![](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/model-zoo/unstructured-weight-sparsity.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=8d496f1311dbe261676016cb713baa69) Weight sparse training methods set subsets of weights to zero. The resulting sparse model requires far fewer FLOPs to train and fewer parameters to store, as multiplies with zeros get skipped on both forward and backward passes through the network. Only systems that can accelerate sparsity, such as Cerebras CS-X and CS-3, can take advantage of the lower resource requirement and use the reduction in FLOPs to significantly accelerate training. Finding and training sparse models to match the accuracy of their original “dense” (i.e., non-sparse) configurations is an active and open area of research! ## Configure Sparsity Let’s expand on the minimal example shown in [sparsity](../../model-zoo/trainer-configuration-overview). For example, with the following config, the sparsity level is set to 0.3 (30%), and `init_method` is `"random"`, which means 30% of the elements in each Parameter (which passes the [default parameter filter](#sparsity-param-filter)) will be pruned once at model initialization and kept that way throughout training. Non-Parameter tensors are not pruned. ```YAML YAML theme={null} trainer: init: ... sparsity: algorithm: "static" sparsity: 0.3 init_method: "random" ... ... ``` ```Python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( ..., sparsity=cstorch.sparse.Static( sparsity=0.5, init_method="random", ), ..., ) ... ``` Sparsity is parameterized primarily by the following keys: * `algorithm`:You can also define a custom class that inherits from [`SparsityAlgorithm`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.SparsityAlgorithm). * Sparsity training algorithm to apply. * [`Static`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.Static) (Default): Fixed sparsity level throughout training * [`GMP`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.GMP): Gradual magnitude pruning * [`SET`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.SET): Sparse Evolutionary Training * [`RigL`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.RigL): Rigging the Lottery ```python theme={null} import cerebras.pytorch as cstorch class CustomSparsity(cstorch.sparse.SparsityAlgorithm): ... ``` * YAML: As long as the class in the global scope, it can be directly used in a YAML config, e.g. * Python: The CustomSparsity class can be passed directly to the Trainer as seen below. ```YAML YAML theme={null} trainer: init: sparsity: algorithm: CustomSparsity ... ``` ```Python python theme={null} from cerebras.modelzoo import Trainer trainer = Trainer( ..., sparsity=CustomSparsity(...), ..., ) ``` See Writing a Custom Sparsity Algorithm for more details on how to write a custom sparsity algorithm. * `sparsity`:The desired sparsity level between 0 and 1. 0.0 means the Parameter is kept fully dense. 1.0 means the Parameter is effectively entirely zeros. Dynamic sparsity algorithms also accept more complex configuration described below in [Dynamic Hyperparameters](#dynamic-hyperparameters). > [!NOTE] > > The actual sparsity level may not match the target sparsity level in practice. The target sparsity level only represents a target distribution. The true sparsity level is determined by the size of the Parameter that is being sparsified. > > For example, if you were to sparsify a Parameter with shape (5,) targeting a sparsity level of 0.5, the actual sparsity level will only ever be 0.4. The smaller the Parameter, the more extreme this discrepancy becomes. If the Parameter is a scalar tensor, then the actual sparsity level will always either be 0.0 or 1.0. * `init_method` optional:Method to compute the initial sparsity distribution. * [`random`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.init.random): (default) Sparsity is randomly distributed within each weight. * [`topk`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.init.topk): Sparsity is distributed according to the lowest magnitude weights. * [`from_zeros`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.init.from_zeros): Sparsity pattern is determined by weight values that are already zero. * `param_filter` optional:Controls which Parameters are sparsified. The list of Parameter names can be found using `model.named_parameters()`. When this is omitted, any multidimensional Parameters (except those with `embedding`, `norm`, or `lm_head` in their name) automatically get sparsity applied (single dimensional weights such as biases are ignored) (See [`default_sparse_param_filter`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.configure.default_sparse_param_filter)).While this provides a good default heuristic for transformer based models [1](#conv), a (list of) glob expressions can also be provided to only apply sparsity to Parameters which match, e.g.\`\`\`Bash trainer: init: sparsity: ... param\_filter: * "\*dense\_layer.weight" * "\*linear\_layer.weight" \`\`\`To match all weights, set `param_filter: *`Per-layer sparsity options can be configured by passing in a list of configuration dictionaries. See below in [advanced param\_filters](#advanced-param-filters). ### Dynamic Sparsity Update Schedule Dynamic sparsity (e.g. [`GMP`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.GMP), [`SET`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.SET), or [`RigL`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.RigL)) needs an additional `update` schedule indicating when to update the sparsity pattern. There are 2 basic methods built-in with 3 different options: #### Regular Interval When sparsity should be updated at a regular interval, a single frequency can be given: ```YAML YAML theme={null} trainer: init: sparsity: update: freq: 100 algorithm: set sparsity: 0.9 ``` ```Python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( ..., sparsity=cstorch.sparse.SET( sparsity=0.9, update=dict(freq=100), ), ..., ) ``` Here, sparsity will be initialized at 90% and steps 0,…,99 will be performed with a fixed sparsity pattern. Every 100 steps, the sparsity pattern will be updated according to the SET algorithm. To control beginning and ending steps, use a dictionary. In the following example, sparsity will be initialized at 0% and steps 0,…,76 will be performed without sparsity. Starting from step 77 and every 100 steps until step 377, the sparsity pattern will be updated according to the SET algorithm. After step 377, the sparsity pattern will continue to be applied, but it will no longer be updated (stop is exclusive). ```YAML YAML theme={null} trainer: init: sparsity: update: start: 77 freq: 100 stop: 477 # An update will _not_ be performed on step 477 algorithm: set sparsity: 0.9 ``` ```Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( ..., sparsity=cstorch.sparse.SET( sparsity=0.9, update=dict( start=77, freq=100, stop=477, # An update will _not_ be performed on step 477 ), ), ..., ) ``` #### Irregular Interval When sparsity should be updated at arbitrary steps, specify them in a list: ```YAML YAML theme={null} trainer: init: sparsity: update: steps: [0, 5, 20, 50] algorithm: set sparsity: 0.9 ``` ```Python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( ..., sparsity=cstorch.sparse.SET( sparsity=0.9, update=dict( steps=[0, 5, 20, 50], ), ), ..., ) ``` ### Dynamic Hyperparameters Dynamic sparsity algorithms (e.g. [`GMP`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.GMP), [`SET`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.SET), or [`RigL`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.RigL)) can configure the `sparsity` (and `drop_fraction` for [`SET`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.SET) and [`RigL`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.RigL)) field using a “step aware hyperparemeter” akin to learning rate schedules in addition to simple constants. These more complex configurations usually require additional options and so are specified as dictionaries. > [!NOTE] > > Note > > The base [`DynamicSparsityAlgorithm`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.DynamicSparsityAlgorithm) that invokes such a dynamic hyperparameter for `sparsity` ensures sparsity levels stay legal by using `torch.clamp(sparsity, min=0.0, max=1.0)`. #### [`Linear`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.utils.Linear) $$ y(\text{step}) = \text{init} + \text{slope} \cdot \text{step} $$ ```YAML YAML theme={null} trainer: init: sparsity: algorithm: "gmp" update: freq: 1000 schedule: type: "linear" init: 0.0 # value at step zero slope: 0.001 # increase in value each step ``` ```Python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( ..., sparsity=cstorch.sparse.GMP( sparsity=cstorch.sparse.utils.Linear( init=0.0, # value at step zero slope: 0.001, # increase in value each step ), update=dict(freq=1000), ), ..., ) ``` #### [`Exponential`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.utils.Exp) $y(\text{step}) = \text{final} + (\text{init} - \text{final}) e^{(\text{step} - \text{gamma})}$ This is expecially useful for [`GMP`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.GMP), where the sparsity level monotonically increases throughout training because a fraction of the remaining elements in the Parameter are pruned at each update step, asymptotically approaching an empty network. ```YAML YAML theme={null} trainer: init: sparsity: algorithm: "gmp" update: freq: 1000 schedule: type: "exp" init: 0.0 # starting value final: 1.0 # asymptotic ending value # Prune 10% of the remaining connections every 1000 steps gamma: -0.00010536051 # ln(1-0.10)/1000 ``` ```Python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( ..., sparsity=cstorch.sparse.GMP( sparsity=cstorch.sparse.utils.Exp( init=0.0, # starting value final=1.0, # asymptotic ending value # Prune 10% of the remaining connections every 1000 steps gamma=-0.00010536051, # ln(1-0.10)/1000 ), update=dict(freq=1000), ), ..., ) ``` #### [`Cosine`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.utils.Cosine) $$y(\text{step}) = o + a \cdot \cos\left(\text{step} \cdot \pi / \text{half_period}\right), \quad \text{where} \quad o = \frac{(\text{init} + \text{minimum})}{2} \text{ and } a = \text{init} - o. $$ This is especially useful for [`RigL`](https://training-api.cerebras.ai/en/latest/wsc/api/cerebras_pytorch/sparse.html#cerebras.pytorch.sparse.RigL), which usually uses a “cosine decay” on its `drop_fraction`. `minimum` defaults to `0.0`. `half_period` controls what step the value reaches its minimum. ```YAML YAML theme={null} trainer: init: sparsity: algorithm: "rigl" update: freq: 1000 sparsity: 0.9 drop_fraction: type: "cosine" init: 0.3 # starting value half_period: 10000 # reaches minimum (default 0) after 10 updates ``` ```Python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( ..., sparsity=cstorch.sparse.RigL( sparsity=0.9, update=dict(freq=1000), drop_fraction=cstorch.sparse.utils.Cosine( init=0.3 # starting value half_period=10000, # reaches minimum (default 0) after 10 updates ), ), ..., ) ``` ### More Config examples The most basic configuration, applying random 30% sparsity to all Parameters: ```YAML YAML theme={null} trainer: init: sparsity: 0.3 ``` ```Python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( ..., sparsity=cstorch.sparse.Static(sparsity=0.3), ..., ) ``` Apply uniform (static) sparsity to a selected set of weights, with a sparsity pattern guided by the weight magnitudes: ```YAML YAMl theme={null} trainer: init: sparsity: sparsity: 0.9 init_method: "topk" param_filter: - "dense_layer.weight" - "linear_layer.weight" ``` ```Python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( ..., sparsity=cstorch.sparse.Group( { "dense_layer.weight": cstorch.sparse.Static( sparsity=0.9, init_method="topk", ), "linear_layer.weight": cstorch.sparse.Static( sparsity=0.9, init_method="topk", ), } ), ..., ) ``` Basic dynamic sparsity using the SET algorithm. Update the sparsity pattern every 1000 iterations. ```YAML YAML theme={null} trainer: init: algorithm: "set" sparsity: 0.9 update: freq: 1000 drop_fraction: 0.3 ``` ```Python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( ..., sparsity=cstorch.sparse.Set( sparsity=0.9, update=dict(freq=1000), drop_fraction=0.3, ), ..., ) ``` ### Configuring Multiple Sparsity Algorithms Different groups of Parameters can be sparsified using different sparsity algorithms. For example, if one set of weights should be statically sparsified to say `0.3`, but another set of weights should be dynamically sparsified using the SET algorithm, it can be done by providing a list of sparsity algorithms. ```YAML YAML theme={null} trainer: init: sparsity: - param_filter: "fc1.*" sparsity: 0.3 - param_filter: "fc2.*" algorithm: "set" sparsity: 0.9 update: freq: 1000 drop_fraction: 0.3 ``` ```Python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer trainer = Trainer( ..., sparsity=cstorch.sparse.Group( { "fc1.*": cstorch.sparse.Static(sparsity=0.3), "fc2.*": cstorch.sparse.SET( sparsity=0.9, update=dict(freq=1000), drop_fraction=0.3, ), } ), ..., ) ``` #### Advanced `param_filters` When each Parameter (or group of Parameters) needs different configuration, `param_filters` can be specified as a dictionary, mapping “patterns” to the config dictionaries to overlay on the default sparsity config options. For example, when using RigL on transformer networks (uses gradient information to guide which values in a Parameter to prune), sparsity can be cyclically restributed between the heads of attention projection weights in case samples in a batch activate one head disproportionately to another. This ultimately decreases the effectiveness of dynamic sparsity and even can hurt model performance. To ensure sparsity is fairly distributed between the different attention heads of the multi-head attention projections, you can specify `balance_out_groups` when the *output* logits are logically N independent/stacked groups (i.e. input projection weights before multi-head attention QKV), or `balance_in_groups` for the reverse (i.e. output projection weights). These should apply differently to different weights using `param_filter` since this conceptually only applies to Attention projection weights. In the following example, the model has 12 attention heads. ```YAML YAML theme={null} rigl_config: &rigl-config algorithm: "rigl" sparsity: 0.9 update: freq: 1000 drop_fraction: type: "cosine" init: 0.3 half_period: 10000 trainer: init: sparsity: - <<: *rigl-config param_filter: "*proj_[qkv]_dense_layer.weight": balance_out_groups : 12 # ensure this matches model.num_heads - <<: *rigl-config param_filter: "*linear_layer.weight": ``` ```Python Python theme={null} rigl_config: &rigl-config algorithm: "rigl" sparsity: 0.9 update: freq: 1000 drop_fraction: type: "cosine" init: 0.3 half_period: 10000 trainer: init: sparsity: - <<: *rigl-config param_filter: "*proj_[qkv]_dense_layer.weight": balance_out_groups : 12 # ensure this matches model.num_heads - <<: *rigl-config param_filter: "*linear_layer.weight": ``` ## Running a Sparse Model No change is needed to the `run` command (see guide: [Launch your job](../../fundamentals/launch-your-job#cs-appliance)) - ensure the `.yaml` file has sparsity enabled. To validate your sparsity config before launching training, run with `--validate_only`. You can also log which weights are being sparsified by passing `--logging VERBOSE` to your run command. ```Bash theme={null} python modelzoo/path/model/run.py CSX \ --params params_with_sparsity.yaml \ --num_csx=1 \ --model_dir model_dir --mode {train,eval,eval_all,train_and_eval} \ --mount_dirs {paths modelzoo and to data} \ --python_paths {paths to modelzoo and other python code if used} ``` When using dynamic sparsity, you can see realtime summaries by using the [`LogSparsity`](https://training-api.cerebras.ai/en/latest/wsc/Model-zoo/api/generated/cerebras.modelzoo.trainer.callbacks.html#cerebras.modelzoo.trainer.callbacks.LogSparsity) callback. YAMLPython ```YAML YAML theme={null} trainer: init: sparsity: ... callbacks: - LogSparsity: {} ``` ```Python Python theme={null} import cerebras.pytorch as cstorch from cerebras.modelzoo import Trainer from cerebras.modelzoo.trainer.callbacks. trainer = Trainer( ..., sparsity=..., callbacks=[LogSparsity()], ..., ) ``` ![](https://mintcdn.com/cerebras-training/v-8ckzus28Y4flPh/rel-2.5.0/images/model-zoo/sparsity-summaries.png?fit=max\&auto=format\&n=v-8ckzus28Y4flPh\&q=85\&s=c775efed04f99886eebdf8528023fa2b) ## Sparsity via API Please see [Sparsifying models](../../model-zoo/tutorials/train-a-model-with-weight-sparsity#sparsity-api) for more details on how to configure sparsity using the Cerebras PyTorch API. ## Related research Sparsity is a powerful tool that can improve performance, reduce the model size, and help [generalizability](https://openreview.net/forum?id=SYuJXrXq8tw) while achieving the same accuracy as densely trained models. Read some of our research work on training with sparsity here: 1. Sparse pre-training and dense fine-tuning (SPDF): [blog](https://www.cerebras.net/blog/accelerating-large-gpt-training-with-sparse-pre-training-and-dense-fine-tuning/), [arxiv](https://arxiv.org/abs/2303.10464/), [PMLR](https://proceedings.mlr.press/v216/thangarasa23a.html). This work shows how we can pre-train a 1.3B parameter GPT-3 style model with up to 75% unstructured sparsity and 60% fewer training FLOPs on Cerebras CS-X, without significantly losing accuracy on downstream tasks. ![](https://mintlify.s3.us-west-1.amazonaws.com/cerebras-training/rel-2.5.0/model-zoo/images/model-zoo/spdf.svg) 1. Sparse Iso-FLOP transformations for Maximizing Training Efficiency (Sparse-IFT): [blog](https://www.cerebras.net/blog/can-sparsity-make-ai-models-more-accurate), [arxiv](https://arxiv.org/abs/2303.11525). This work shows how pre-training a GPT-3 style small model with sparsity leads to a 0.4 perplexity improvement on the WikiText103 language modeling task. See the table below and paper for more details, including results on computer vision tasks. ![](https://mintlify.s3.us-west-1.amazonaws.com/cerebras-training/rel-2.5.0/model-zoo/images/model-zoo/sparse-ift.png) 1. Variable Sparse pre-training and dense fine-tuning (Variable SPDF): [blog](https://www.cerebras.net/blog/accelerating-llm-training-with-variable-sparse-pre-training-and-dense-fine-tuning/?utm_content=258048089\&utm_medium=social\&utm_source=linkedin\&hss_channel=lcp-10858000). This work extends SPDF, demonstrating the scaling up to a 6.7B GPT-3 style model with a 64% FLOPs reduction while maintaining downstream model performance. This is accomplished by performing the majority of pre-training at static sparsity, then finishing pre-training on a dense version of the model before fine-tuning on the dense version as well. ![](https://mintlify.s3.us-west-1.amazonaws.com/cerebras-training/rel-2.5.0/model-zoo/images/model-zoo/vspdf.svg) ## Footnotes Sparsity on CSX has not yet been thoroughly validated with convolutional networks. # Train LLMs with μP: Legacy Parameters Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/tutorials/train-an-llm-using-maximal-update-parameterization-with-legacy-params Learn how to train an LLM with maximal update parameterization (μP). GPT-style models are commonly trained using Standard Parametrization (SP) where model weights are initialized from normal distributions with constant standard deviation or standard deviation based on the shape of each layer. However, as models scale to many parameters, the parametrization does not account for potential inter-layer interactions, resulting in unstable training. This instability can cause costly restarts. Further, hyperparameters do not transfer well as models scale in size. We can address these challenges by using [μP (Maximal Update Parameterization)](https://arxiv.org/abs/2203.03466) μP by enabling: * Stable training dynamics at a large scale by controlling the initialization, activations magnitude, and layer-wise adaptive learning rates independent of model width * Zero-shot hyperparameter transfer from a smaller model to larger model. Essentially, μP facilitates width invariance to the model’s hyperparameters. For example, if the [Cerebras-GPT](https://arxiv.org/pdf/2304.03208.pdf) family of models was trained using both SP and μP parametrizations. For SP configuration, the hyperparameters were chosen from the best results found in the literature. For μP configurations, μTransfer enabled scaling hyperparameters from a 40M parameter model to models up to 2.7B parameters, resulting in a lower loss. These results highlight how μP can improve large model scaling, improving accuracy, and hyperparameter predictability at scale. > [!NOTE] > > Appendix G in [Cerebras-GPT paper](https://arxiv.org/pdf/2304.03208.pdf) contains the learnings from the Cerebras team while using μP parametrization, including implementation differences with versus SP parametrization, μP hyperparameter search details, and advice for practitioners regarding the critical batch size. > > In particular, we suggest looking at **Table 14: Cheat Sheet: All implementation details required to compare SP and μP**, to identify differences between μP and SP parametrizations. ## Procedure GPT-2, GPT-3, Bloom, Llama, Falcon, Starcoder, and MPT with decoder-only architecture and autoregressive language modeling objective are supported by μP parameterizaiton. μP works with differet types of position embeddings such as ALiBi, RoPE, Relative and Fixed position embeddings, with efficient attention architectures like Multi-Query Attention, and activation functions such as SwiGLU. All configuration files in these models are SP parametrized unless noted as `_mup.yaml`. You can find SP and μP parametrizations in the Cerebras Model Zoo. For more information, refer to the configuration yaml files. **1.** Execute both config files using the `run.py` script of the preferred GPT-style model. **2.** Specify the path to the config file using the `--config` flag. For more information on launching a Cerebras job, visit [the Quickstart guide](../../quickstart/home). ## Differences between SP and μP parametrization ### Structure μP parametrization has additional hyperparameters that scale internal layers, including adding element-wise activation tensor scaling and adding layer-wise learning rates scaling to certain layers. These hyperparameters are specified in the config file as follows: ```Bash theme={null} model: ... # muP scale_qk_dot_by_d: True output_logits_scale: ... embeddings_scale: ... optimizer: ... adjust_learning_rate: decoder_kernel: ... ``` ### Initialization values μP parametrization requires adjusting initializers for affected layers. Also, these hyperparameters are intended to be derived using μTransfer approach instead of reproducing results found in the literature. In the next section, you will learn more about computing values for μTransfer approach. > [!NOTE] > > Note > > To learn more about the mathematical differences between μP and SP, we suggest **Table 14: Cheat Sheet: All implementation details required to compare SP and μP**, in the Appendix G of [Cerebras-GPT paper](https://arxiv.org/pdf/2304.03208.pdf). You can find examples of and μP parametrization in the [configurations of Cerebras-GPT](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/Cerebras_GPT) for models of the same size, including Cerebras-GPT of 2.7B parameters using [sP](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/mz/Cerebras_GPT/2p7b.yaml) and [muP](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/mz/Cerebras_GPT/2p7b_mup.yaml) parametrizations. ## Transfering hyperparameters [μTransfer](https://openreview.net/pdf?id=Bx6qKuBM2AD) is a hyperparameter transfer paradigm that makes zero-shot transfer of near-optimal hyperparameters possible from a small version of the model to a large model via μP (Maximal Update Parameterization). The “small model” is called the *proxy-model* for which the hyperparameters are tuned, and the “large model” is referred to as the *target-model*. First, you will tune nearly optimal hyperparameters of the “proxy-model”. In particular, the optimal learning rate, the initialization standard deviation, and the embedding multiplier will be relevant to derive scaling formulas for the “target-model”. As an example, the [Cerebras-GPT](https://arxiv.org/pdf/2304.03208.pdf) family used a 200 sample random hyperparameter search on a 40M parameter proxy model trained on 600M tokens with a batch size of 131k tokens. You can find results and details on the optimal hyperparameters in Appendix G of the paper. Second, you will scale up the hyperparameters based on the size of the *target-model*. For this, it is helpful to identify the different types of hyperparameters in a GPT-style model: | μTransferred Across | μTransferable | Not μTransferable | | - | - | - | | They define the training scale | They can transfer from the small to the large model | They do not work with μTransfer, because they depend on model size and data size | | Theoretically demonstrated: width; Empirically demonstrated: depth, batch size,training time, seq length | Optimization related (learning rate (LR), momentum, Adam beta, LR schedule, etc), inititalization (per-layer init. variance),parameter multipliers (multiplicative constants after weight/biases) | Regularization (dropout, weight decay, etc) | Scaling the hyperparameter values from proxy to target model is defined by a series of equations depending on the *layer width multiplier* $(m_{width} = d_{target}/d_{proxy})$, where $d$ stands for the width of each layer. For example, let's use the 40M parameter Cerebras-GPT model as a proxy model and 2.7B parameter Cerebras-GPT model as the target model. The 40M model has a hidden size of 256, and the 2.7B model has a hidden size of 2560. Thus $d_{proxy} = 256$, $d_{target} = 2560$, and $m_{width} = d_{target}/d_{proxy} = 10$. These equations are found in Table 14 Appendix G of [Cerebras-GPT paper](https://arxiv.org/pdf/2304.03208.pdf). For convenience, Cerebras Model Zoo contains the script [convert\_config\_to\_mup.py](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/tools/convert_config_to_mup.py) to scale GPT-3 configurations based on a *target-model* configuration YAML file. This script has the following parameters: | Parameter | Description | | - | - | | `--input_yaml` or `-i` | \[Required] Configuration Yaml file of the *target-model*. This can be a standard configuration file, like the ones found in [Cerebras Model Zoo](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gpt3/configs) | | `--base_layer_width` or `-d_base` | \[Optional] Proxy-model’s width, defaults to 256 | | `--base_lr or -lr_base` | \[Optional] Proxy-model’s lr determined by hyperparameter sweep, defaults to 6e-3. Currently, we support config generation for sequential Linear learning rate schedules. First lr scheduler should perform linear warm-up and second scheduler should do linear decay. | | `--base_init_std` or `-std_base` | \[Optional] Proxy-model’s initial standard deviation, defaults to 0.08 | | `--m_embed` or `-m_base` | Proxy-model’s embeddings multiplier, defaults to 10.0 | | `--output_yaml` or `-o` | \[Optional] Output yaml file to save the μP config. if not provided, config will be stored under the same path as the input but with a `_mup` tag | ## Implementation notes The default values of these parameters are based on the findings in the [Cerebras-GPT paper](https://arxiv.org/pdf/2304.03208.pdf), with a proxy model of 40M parameters. For example, you can use this script with a configuration file of a GPT-3 model of 2.7B params, called `params_gpt3_2p7b.yaml` and all of the default arguments as follows: ```Bash theme={null} python convert_config_to_mup.py --input_yaml /params_gpt3_2p7b.yaml ``` ```Bash theme={null} muP config saved to </path/to/config>/params\_gpt3\_2p7b_mup.yaml ``` ## Best Practices When picking the best configuration of the μP hyperparameters from your hyperparameter sweep, it is recommended to pick top-10 configurations from the `40M` base model with the best validation loss. Let’s say the goal is to transfer the hyperparameters to 13B model scale, it is advised to first transfer the hyperparameters to an intermediate sized model size such as `256M` or `590M`. At `256M` or `590M` scale, run training with the `top-10` configs for `20` tokens per parameter and evaluate the model using a validation set. To pick the best configuration from validation loss metric, it is recommended to not just look at the lowest loss value but also the training dynamics. In our experience, for some configurations you may see very low loss values but few instabilities in the training dynamics (which manifest as loss spikes or exploding gradient norm). In that scenario it is best to pick a configuration with second or third best validation loss which exhibit stable training dynamics. Consult the base μP configuration for the GPT-3 model, available at [40M config](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/mz/muP/params_gpt3_40M.yaml). This configuration was employed internally for our hyperparameter optimization processes. Subsequently, we applied μTransfer techniques to upscale to the [256M model](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/mz/muP/params_gpt3_256M.yaml). For different model architectures like Llama and Falcon, it’s necessary to develop a new 40M configuration that aligns with their specific structural requirements. If there is a significant change in the model architecture such as changing position embeddings from `Relative` to `RoPE` or `ALiBi`, changing activation function from `GeLU` to `SwiGLU`, it is advised to redo the hyperparameter sweep at 40M scale to pick the best configs. In such cases, using the optimal set of hyperparameters from [Cerebras-GPT paper](https://arxiv.org/pdf/2304.03208.pdf) is not recommended. ## Related research 1. Radford, A. et al. (2019). [Language Models are Unsupervised Multitask Learners](https://d4mucfpksywv.cloudfront.net/better-language-models/language-models.pdf). 2. Brown, T.B. et al. (2020). [Language Models are Few-Shot Learners](https://arxiv.org/abs/2005.14165). 3. Yang, G. et al. (2022). [Tensor Programs V: Tuning Large Neural Networks via Zero-Shot Hyperparameter Transfer](https://arxiv.org/abs/2203.03466). 4. Dey, N. et al. (2023). [Cerebras-GPT: Open Compute-Optimal Language Models Trained on the Cerebras Wafer-Scale Cluster](https://arxiv.org/abs/2304.03208). # Train an LLM with a Large or Small Context Window Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/tutorials/train-an-llm-with-a-large-or-small-context-window ## Overview One of the advantages of the CS-X is the ability to train a Large Language Model (LLM) with a large context window (also known as sequence lengths). Larger context windows enable LLMs to handle larger inputs. Sometimes it is advantageous to train with a shorter context window (e.g., in instruction tuning) for efficiency. Follow the steps in this guide to train a language model with a large (> 2048) or a small (\< 2048) context window. ## Procedure ### For large context window **1.** Data processing: when creating your dataset using the script file `create_hdf5_dataset.py`, change the value of the argument `--max_seq_length` to the desired value. For example, for a sequence length of 4096 tokens: ```Bash theme={null} python create_hdf5_dataset.py LMData \ --input_dir /path/to/data \ --tokenizer_type NeoXTokenizer \ --encoder_file /path/to/encoder \ --max_seq_length 4096 \ --ftfy True \ --pack_sequences False ``` **2.** Model training: after processing your data, set the `max_sequence_length` and the `max_position_embeddings` to the desired value in the model’s configuration YAML file. For example: ```Bash theme={null} trainer: init: ... model: ... max_position_embeddings: 4096 ... ... fit: train_dataloader: data_processor: "GptHDF5DataProcessor" data_dir: ./path/to/train/dataset/with_msl4096/ max_sequence_length: 4096 ... val_dataloader: data_processor: "GptHDF5DataProcessor" data_dir: "./path/to/eval/datast/with_msl4096" max_sequence_length: 4096 ... ... ``` ### For small context window For example, a model that was pretrained on a sequence length of 2048 tokens may be further instruction fine-tuned on a dataset with a sequence length of 256 tokens. In this case assume the longest sequence in the dataset has a length of 256 tokens. Since the sequences of this dataset will be padded, not packed, training with a shorter sequence length is more efficient than padding every sample in the dataset all the way to 2048 tokens. **1.** Data processing: when calling the script file `create_hdf5_dataset.py`, change the value of the argument `--max_seq_length` to the desired value. ```Bash theme={null} python create_hdf5_dataset.py Summarization \ --input_dir /path/to/data \ --tokenizer_type NeoXTokenizer \ --encoder_file /path/to/encoder \ --max_seq_length 256 \ --ftfy True \ --sep_token: null \ --prompt_key: "prompt" \ --completion_key: "completion" \ --pack_sequences False ``` **2.** Model training: after processing your data, set the `max_sequence_length` to the desired value in the model’s configuration `yaml` file. For example: ## Implementation notes Note when training a pretrained model with a smaller context window, the `max_position_embeddings` parameter of the pretrained model remains the same. Only the `max_sequence_length` parameter needs to be changed. On the other hand, when training with a large context window, both the `max_position_embeddings` and `max_sequence_length` parameters need to be changed. ## Conclusion Training a Large Language Model (LLM) with an appropriately sized context window is crucial for optimizing its performance and efficiency. By adjusting the context window size, whether large or small, users can tailor the training process to suit specific requirements, such as handling larger inputs or improving efficiency during instruction fine-tuning. The process involves careful preparation of the dataset and precise configuration of model parameters to ensure that the LLM can effectively learn from and generate text based on the given context size. Ultimately, understanding and leveraging the context window’s impact on LLM training allows for more flexible and powerful model applications, enabling users to achieve their desired outcomes with greater precision and efficiency. # Configure μP for Bert Pretrain Beta Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/tutorials/training-an-llm-using-maximal-update-parameterization/configure-mp-for-bert-pretrain--beta > [!NOTE] > > Beta support indicates that we have confirmed the model’s μP functionality using coordinate checks, but have yet to perform long convergence runs. ## Model Params * `mup_base_hidden_size` (Required to enable μP):The hidden size of the proxy model in μP transfer used to calculate the necessary multipliers. * `mup_base_filter_size` (Required to enable μP):The filter size of the proxy model in μP transfer used to calculate the necessary multipliers. * `embeddings_scale`:Scales the embedding hidden states (i.e. the tensor after embeddings & embedding layer norm are applied). Recommended to tune for stabilizing gradient flow during μP training. * `output_logits_alpha`:Constant applied to the output logits scalar in μP training. The output logits are scaled by `output_logits_alpha * mup_base_hidden_size/hidden_size`. Recommended to tune for stabilizing output logits in μP training. * `scale_qk_dot_by_d`:Scales attention QK dot product by d instead of sqrt(d). Must be enabled for muP training. * `attention_logits_alpha`:Scales the attention QK dot product by the specified value. Recommended to tune for stabilizing attention logits in muP training. * `scale_output_logits_by_d`:Scales the output logits in μP by `mup_base_hidden_size/hidden_size` if True and `sqrt(mup_base_hidden_size/hidden_size)` if False. It is traditionally set to `True` in the μP implementation of this model. ## Supported LR Adjustment Groups * `embedding`: Targets the embedding weights. * `encoder_attention`: Targets the dense layers in the encoder (Q, K, V, Output projections) * `encoder_input_ffn`: Targets the first of the two FFN blocks in the encoder. * `encoder_output_ffn`: Targets the final FFN block in the encoder. * `pooler`: Targets the pooler FFN. ## Example Configuration ```Bash theme={null} model: ... # muP scale_qk_dot_by_d: True scale_output_logits_by_d: True mup_base_hidden_size: ... mup_base_filter_size: ... output_logits_alpha: ... attention_logits_alpha: ... embeddings_scale: ... optimizer: ... adjust_learning_rate: embedding: ... encoder_input_ffn: ... ... ``` Note how not all the LR adjustment groups were specified since there is only a need to provide these values in the config if you would like to override the traditional μP LR scaling. # Configure μP for GPT Style Models Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/tutorials/training-an-llm-using-maximal-update-parameterization/configure-mp-for-gpt-style-models > [!NOTE] > > Beta support for GPTJ indicates that we have confirmed the model’s μP functionality using coordinate checks, but have yet to perform long convergence runs. ## Model Params * `mup_base_hidden_size` (Required to enable μP):The hidden size of the proxy model in μP transfer used to calculate the necessary multipliers. * `mup_base_filter_size` (Required to enable μP):The filter size of the proxy model in μP transfer used to calculate the necessary multipliers. * `embeddings_scale`:Scales the embedding hidden states (i.e. the tensor after embeddings & embedding layer norm are applied). Recommended to tune for stabilizing gradient flow during μP training. * `output_logits_alpha`:Constant applied to the output logits scalar in μP training. The output logits are scaled by `output_logits_alpha * mup_base_hidden_size/hidden_size`. Recommended to tune for stabilizing output logits in μP training. * `scale_qk_dot_by_d`:Scales attention QK dot product by d instead of sqrt(d). Must be enabled for muP training. * `attention_logits_alpha`:Scales the attention QK dot product by the specified value. Recommended to tune for stabilizing attention logits in muP training. * `scale_output_logits_by_d`:Scales the output logits in μP by `mup_base_hidden_size/hidden_size` if True and `sqrt(mup_base_hidden_size/hidden_size)` if False. It is traditionally set to `True` in the μP implementation of this model. ## Supported LR Adjustment Groups * `embedding`: Targets the embedding weights. * `decoder_attention`: Targets the dense layers in the decoder (Q, K, V, Output projections) * `decoder_input_ffn`: Targets the first of the two FFN blocks in the decoder. * `decoder_output_ffn`: Targets the final FFN block in the decoder. ## Example Configuration ```bash theme={null} model: ... # muP scale_qk_dot_by_d: True scale_output_logits_by_d: True mup_base_hidden_size: ... mup_base_filter_size: ... output_logits_alpha: ... attention_logits_alpha: ... embeddings_scale: ... optimizer: ... adjust_learning_rate: embedding: ... decoder_input_ffn: ... ... ``` Note how not all the LR adjustment groups were specified since there is only a need to provide these values in the config if you would like to override the traditional μP LR scaling. # Configure μP for T5 Beta Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/tutorials/training-an-llm-using-maximal-update-parameterization/configure-mp-for-t5--beta > [!NOTE] > > Beta support indicates that we have confirmed the model’s μP functionality using coordinate checks, but have yet to perform long convergence runs. > > T5 support places many more limitations on the model than the others: > > * μP is only supported with `use_transformer_initialization` set to `False`. > > * Using Adafactor as usual with T5 in contrast to using the usual Adam optimizers in our other μP models may cause instability. > > * Varying `d_kv` and `num_heads` between the proxy model and the target model may cause instability. ## Model Params * `mup_base_d_model` (Required to enable μP):The d\_model of the base model in μP transfer used to calculate the necessary multipliers. * `mup_base_d_ff` (Required to enable μP):The d\_ff of the base model in μP transfer used to calculate the necessary multipliers. * `mup_base_d_kv` (Highly Experimental):The d\_kv of the base model in μP transfer used to calculate the necessary multipliers. **Only use when varying d\_kv alongside d\_model.** * `embeddings_alpha`:Scales the embedding hidden states (i.e. the tensor after embeddings & embedding layer norm are applied). The embeddings are scaled by `embeddings_alpha * sqrt(d_model)`. Recommended to tune for stabilizing gradient flow during μP training. * ``output_logits_alpha` ``:Constant applied to the output logits scalar in μP training. The output logits are scaled by `output_logits_alpha * mup_base_d_model/d_model`. Recommended to tune for stabilizing output logits in μP training. * `scale_encoder_qk_dot_by_d`:Scales encoder attention QK dot product by d instead of sqrt(d). Must be enabled for μP training. * `scale_decoder_qk_dot_by_d`:Scales decoder attention QK dot product by d instead of sqrt(d). Must be enabled for μP training. * `encoder_attention_logits_alpha`:Additionally scales the encoder attention QK dot product by the specified value. Recommended to tune for stabilizing attention logits in μP training. * `decoder_attention_logits_alpha`:Additionally scales the decoder attention QK dot product by the specified value. Recommended to tune for stabilizing attention logits in μP training. * `scale_output_logits_by_d`:Scales the output logits in μP by `mup_base_d_model/d_model` if `True` and `sqrt(mup_base_d_model/d_model)` if `False`. Unlike other models, the default for the μP implementation in this model is `False`. ## Supported LR Adjustment Groups * `embedding`: Targets the embedding weights. * `encoder_qkv_projection`: Targets the Q, K, V projection dense layers in the encoder. * `encoder_output_projection`: Targets the output projection dense layer in the encoder. * `encoder_input_ffn`: Targets the first of the two FFN blocks in the encoder. * `encoder_output_ffn`: Targets the final FFN block in the encoder. * `decoder_qkv_projection`: Targets the Q, K, V projection dense layers in the decoder. * `decoder_output_projection`: Targets the output projection dense layer in the decoder. * `decoder_input_ffn`: Targets the first of the two FFN blocks in the decoder. * `decoder_output_ffn`: Targets the final FFN block in the decoder. * `lm_head`: Targets the weights of the lm\_head. ## Example Configuration ```Bash theme={null} model: ... # muP scale_encoder_qk_dot_by_d: True scale_decoder_qk_dot_by_d: True scale_output_logits_by_d: False mup_base_d_model: ... mup_base_d_ff: ... output_logits_alpha: ... encoder_attention_logits_alpha: ... decoder_attention_logits_alpha: ... embeddings_alpha: ... optimizer: ... adjust_learning_rate: embedding: ... decoder_input_ffn: ... lm_head: ... ... ``` Note how not all the LR adjustment groups were specified since there is only a need to provide these values in the config if you would like to override the traditional μP LR scaling. # Train LLMs with μP Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/tutorials/training-an-llm-using-maximal-update-parameterization/overview Learn how to train an LLM with maximal update parameterization (μP). In this guide, you will learn how to configure an LLM in [μP (Maximal Update Parametrization)](https://arxiv.org/abs/2203.03466) and perform [μTransfer](https://openreview.net/pdf?id=Bx6qKuBM2AD) in order to transfer optimized hyperparameters from a scaled-down version of the LLM (a “proxy model”) to the target model, thereby reducing the time and cost of hyperparameter sweeps. If you are already familiar with the μP and μTransfer techniques, feel free to skip ahead to [Configuring μP Params For Your Model](#configuring-mup-params). ## Background Transformer models are commonly trained using Standard Parametrization (SP) where model weights are initialized from normal distributions with constant standard deviation or standard deviation based on the shape of each layer. However, as models scale to many parameters, the parametrization does not account for potential inter-layer interactions, resulting in unstable training. This instability can cause costly restarts. Furthermore, hyperparameters do not transfer well as models scale in size. μP addresses these challenges by enabling: * Stable training dynamics at a large scale by controlling the initialization, activations magnitude, and layer-wise adaptive learning rates independent of model width. * Zero-shot hyperparameter transfer from a smaller model to larger model. Essentially, μP facilitates width invariance to the model’s hyperparameters. For example, the [Cerebras-GPT](https://arxiv.org/pdf/2304.03208.pdf) family of models was trained using both SP and μP parametrizations. For SP configuration, the hyperparameters were chosen from the best results found in the literature. For μP configurations, μTransfer enabled scaling hyperparameters from a 40M parameter model to models up to 2.7B parameters, resulting in a lower loss. These results highlight how μP can improve large model scaling, improving accuracy, and hyperparameter predictability at scale. > [!NOTE] > > Appendix G in [Cerebras-GPT paper](https://arxiv.org/pdf/2304.03208.pdf) contains the learnings from the Cerebras team while using μP, including implementation differences with versus SP, μP hyperparameter search details, and advice for practitioners regarding the critical batch size. > > In particular, we suggest looking at **Table 14: Cheat Sheet: All implementation details required to compare SP and μP**, to identify differences between μP and SP parametrizations. ### Transferring hyperparameters [μTransfer](https://openreview.net/pdf?id=Bx6qKuBM2AD) is a hyperparameter transfer paradigm that makes zero-shot transfer of near-optimal hyperparameters possible from a small version of the model to a large model via μP. The “small model” is called the *proxy-model* for which the hyperparameters are tuned, and the “large model” is referred to as the *target-model*. The μTransfer procedure can be broken down as follows: 1. Tune nearly optimal hyperparameters of the “proxy-model”. In particular, the optimal learning rate, the initialization standard deviation, and the embedding multiplier will be relevant to derive scaling formulas for the “target-model”. As an example, the [Cerebras-GPT](https://arxiv.org/pdf/2304.03208.pdf) family used a 200 sample random hyperparameter search on a 40M parameter proxy model trained on 600M tokens with a batch size of 131k tokens. You can find results and details on the optimal hyperparameters in [Appendix G of the paper](https://arxiv.org/pdf/2304.03208.pdf). 2. Scale up the hyperparameters based on the size of the *target-model*. As of release 2.3, much of this scaling is now automated by default when μP params are specified in the config. > [!NOTE] > > Old configs are still expected to work in the same manner as they did before, see [the legacy μP guide](../model-zoo/tutorials/train-an-llm-using-maximal-update-parameterization-with-legacy-params) for more information. > > Scaling the hyperparameter values from proxy to target model is defined by a series of equations depending on the *layer width multiplier* $M_{\text{width}} = \frac{d_{\text{proxy}}}{d_{\text{target}}}$ where $d$ stands for the width of each layer. For example, let’s use the 40M parameter Cerebras-GPT model as a proxy model and 2.7B parameter Cerebras-GPT model as the target model. The 40M model has a hidden size of 256, and the 2.7B model has a hidden size of 2560. Thus $d_{\text{proxy}} = 256, \, d_{\text{target}} = 2560$, and $m_{\text{width}} = \frac{d_{\text{target}}}{d_{\text{proxy}}} = 10$. These equations are found in Table 14 Appendix G of [Cerebras-GPT paper](https://arxiv.org/pdf/2304.03208.pdf). In a transformer model, it is helpful to identify which hyperparameters can be μTransferred: | **μTransferred Across** (They define the training scale) | **μTransferable** | **Not μTransferable** (They depend on model and data size) | | - | - | - | | Width, Depth, Batch Size, Training Time, Sequence Length | Optimization Params, Per-Layer Initialization Variance, Parameter Multipliers | Regularization Params | * Optimization params: learning rate (LR), momentum, Adam beta, LR schedule, etc. * Regularization params: Dropout, weight decay, etc. * Parameter multipliers describe multiplicative constants that apply to weights/biases (embeddings scale, output logits alpha, etc.) ## Configuring μP Params For Your Model In this example, you will perform μTransfer on a GPT-3 2.7B model using a 40M proxy model. You can enable and configure μP through the model and optimizer params. These parameters differ slightly depending on the backbone of the model for which you want to implement muP, but the overall structure stays the same. The corresponding config for the 2.7B model is: ```Bash theme={null} trainer: init: ... model: ... hidden_size: 2560 filter_size: 10240 num_hidden_layers: 32 embedding_initializer: a: -0.04 b: 0.04 mean: 0.0 name: truncated_normal std: 0.02 initializer: a: -0.04 b: 0.04 mean: 0.0 name: truncated_normal std: 0.02 output_layer_initializer: a: -0.04 b: 0.04 mean: 0.0 name: truncated_normal std: 0.02 attention_type: scaled_dot_product ... optimizer: AdamW: ... precision: ... schedulers: - ... callbacks: ... fit: ... ``` ### Base dimensions For each model, there is a set of base dimensions that are specifiable. They indicate width dimensions of the proxy model from which you are trying to perform hyperparameter transfer and are the bare minimum params required to enable μP scaling. In the case of GPT-3, the supported base dimensions are: * `mup_base_hidden_size` (Required to enable μP): The hidden size of the proxy model. * `mup_base_filter_size` (Required to enable μP): The filter size of the proxy model. > [!NOTE] > > Note > > Upon specifying base dimensions, the corresponding **learning rates, initialization values, and layer activations will be automatically scaled** according to the width ratio of the dimensions provided for the proxy model and the target model. In the case where GPT-3 40M as the proxy model and 2.7B is the target model, you would set `mup_base_hidden_size = 256` and `mup_base_filter_size = 1024` in the config of the target model since they correspond to the `hidden_size` and `filter_size` of the [40M model config](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/muP/params_gpt3_40M.yaml). ### Initialization Values μP requires the addition of initialization scaling for certain layers. As of release 2.3, we now handle this scaling automatically based on the specified base dimensions. We use the width ratio of the dimensions and base dimensions to scale the standard deviation of the corresponding layers’ initializers. In addition to this, we also scale the initializers of the encoder/decoder output projection layers by `2 * num_(encoder/decoder)_blocks` to aid with transferring across depth. > [!NOTE] > > Note > > For models in which custom initializers can be specified, μP scaling is only compatible with Normal and Truncated Normal distributions. ### Hyperparameters While specifying the required base dimensions is the bare minimum requirement to enable μP scaling on the model, it is necessary to additionally specify some μP specific hyperparameters to obtain better performance and stability in the model. These parameters modify the way we scale the embeddings, output logits, and the attention module projections in the transformer to stabilize gradient flow during training. For GPT-3, the following μP hyperparameters are supported: * `embeddings_scale`: Scales the embedding hidden states (i.e. the tensor after embeddings & embedding layer norm are applied). Recommended to tune for stabilizing gradient flow during μP training. * `output_logits_alpha`: Constant applied to the output logits scalar in μP training. The output logits are scaled by `output_logits_alpha * mup_base_hidden_size/hidden_size`. Recommended to tune for stabilizing output logits in μP training. * `scale_qk_dot_by_d`: Scales attention QK dot product by d instead of sqrt(d). Must be enabled for muP training. * `attention_logits_alpha`: Scales the attention QK dot product by the specified value. Recommended to tune for stabilizing attention logits in muP training. * `scale_output_logits_by_d`: Scales the output logits in μP by `mup_base_hidden_size/hidden_size` if True and `sqrt(mup_base_hidden_size/hidden_size)` if False. It is traditionally set to `True` in the μP implementation of this model. ### LR Adjustment Groups μP requires the addition of layer-wise scaling of learning rates to certain layers. As of release 2.3, we now handle this scaling automatically based on the specified base dimensions. The base dimensions are used to calculate the necessary scales on preset LR adjustment groups that apply the scale to layers that correspond to the group. Following the GPT-3 example, the supported LR adjustment groups are: * `embedding`: Targets the embedding weights. * `decoder_attention`: Targets the dense layers in the decoder (Q, K, V, Output projections) * `decoder_input_ffn`: Targets the first of the two FFN blocks in the decoder. * `decoder_output_ffn`: Targets the final FFN block in the decoder. You also have the option to override these scales in the YAML by specifying the group in the optimizer params. For example, in order to apply some custom scaling to the embedding weights, you will specify the params as such: ```Bash theme={null} optimizer: ... adjust_learning_rate: embedding: ``` > [!NOTE] > > Note > > For those who are writing their own model or modifying those in Modelzoo, you can easily add new groups or modify existing groups by modifying the `create_default_lr_adjustment_groups` function in the `model.py` of a given model. ### Final Config Putting it all together, the appended params for a GPT-3 2.7B model with a 40M proxy model and custom embedding weights LR scaling would look like this: ```Bash theme={null} model: ... mup_base_hidden_size: 256 mup_base_filter_size: 1024 scale_qk_dot_by_d: True scale_output_logits_by_d: True embeddings_scale: output_logits_alpha: attention_logits_alpha: ... optimizer: ... adjust_learning_rate: embedding: ``` Where `` is a placeholder for a hyperparameter value you can determine via sweeping or some other means and is different for each parameter. Appending those params to the final config: ```Bash theme={null} trainer: init: ... model: ... hidden_size: 2560 filter_size: 10240 num_hidden_layers: 32 embedding_initializer: a: -0.04 b: 0.04 mean: 0.0 name: truncated_normal std: 0.02 initializer: a: -0.04 b: 0.04 mean: 0.0 name: truncated_normal std: 0.02 output_layer_initializer: a: -0.04 b: 0.04 mean: 0.0 name: truncated_normal std: 0.02 attention_type: scaled_dot_product # Maximal Update Parametrization (muP) Settings mup_base_hidden_size: 256 mup_base_filter_size: 1024 scale_qk_dot_by_d: True scale_output_logits_by_d: True embeddings_scale: output_logits_alpha: attention_logits_alpha: ... optimizer: adjust_learning_rate: embedding: AdamW: ... precision: ... schedulers: - ... callbacks: ... fit: ... ``` ## μP-Compatible Models GPT-2, GPT-3, Bloom, Llama, Falcon, Starcoder, and MPT with decoder-only architecture and autoregressive language modeling objective are supported by μP. As of 2.3, we are also providing beta support for GPTJ, T5, and BERT Pretrain models. μP works with different types of position embeddings such as `ALiBi`, `RoPE`, `Relative` and `Fixed` position embeddings, with efficient attention architectures like Multi-Query Attention, and activation functions such as `SwiGLU`. Please refer to the following guides for a detailed breakdown of model-specific μP params: * [Configure μP for GPT-Style Models](../../../model-zoo/tutorials/training-an-llm-using-maximal-update-parameterization/configure-mp-for-gpt-style-models) * [Configure μP for BERT Pretrain (Beta)](../../../model-zoo/tutorials/training-an-llm-using-maximal-update-parameterization/configure-mp-for-bert-pretrain--beta) * [Configure μP for T5 (Beta)](../../../model-zoo/tutorials/training-an-llm-using-maximal-update-parameterization/configure-mp-for-t5--beta) ## Implementation notes GPT and BERT type models are implemented based off Table 8 of the [Tensor Programs V: Tuning Large Neural Networks via Zero-Shot Hyperparameter Transfer paper](https://arxiv.org/pdf/2203.03466), while T5’s implementation is based off Table 9 in order to circumvent some conflicts with its pre-existent initialization scheme. ## Best Practices When picking the best configuration of the μP hyperparameters from your hyperparameter sweep, it is recommended to pick top-10 configurations from the `40M` base model with the best validation loss. Let’s say the goal is to transfer the hyperparameters to 13B model scale, it is advised to first transfer the hyperparameters to an intermediate sized model size such as `256M` or `590M`. At the `256M` or `590M` scale, run training with the `top-10` configs for `20` tokens per parameter and evaluate the model using a validation set. To pick the best configuration from validation loss metric, it is recommended to not just look at the lowest loss value but also the training dynamics. In our experience, for some configurations you may see very low loss values but few instabilities in the training dynamics (which manifest as loss spikes or exploding gradient norm). In that scenario it is best to pick a configuration with second or third best validation loss which exhibit stable training dynamics. Consult the base μP configuration for the GPT-3 model, available at [40M config](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/muP/params_gpt3_40M.yaml). This configuration was employed internally for our hyperparameter optimization processes. Subsequently, we applied μTransfer techniques to upscale to the [256M model](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/gpt3/configs/muP/params_gpt3_256M.yaml). For different model architectures like Llama and Falcon, it’s necessary to develop a new 40M configuration that aligns with their specific structural requirements. If there is a significant change in the model architecture such as changing position embeddings from `Relative` to `RoPE` or `ALiBi`, changing activation function from `GeLU` to `SwiGLU`, it is advised to redo the hyperparameter sweep at 40M scale to pick the best configs. In such cases, using the optimal set of hyperparameters from [Cerebras-GPT paper](https://arxiv.org/pdf/2304.03208.pdf) is not recommended. ## Related research 1. Radford, A. et al. (2019). [Language Models are Unsupervised Multitask Learners](https://d4mucfpksywv.cloudfront.net/better-language-models/language-models.pdf). 2. Brown, T.B. et al. (2020). [Language Models are Few-Shot Learners](https://arxiv.org/abs/2005.14165). 3. Yang, G. et al. (2022). [Tensor Programs V: Tuning Large Neural Networks via Zero-Shot Hyperparameter Transfer](https://arxiv.org/abs/2203.03466). 4. Dey, N. et al. (2023). [Cerebras-GPT: Open Compute-Optimal Language Models Trained on the Cerebras Wafer-Scale Cluster](https://arxiv.org/abs/2304.03208). # Training With Number Of Tokens Loss Scaling Source: https://training-docs.cerebras.ai/rel-2.5.0/model-zoo/tutorials/training-with-number-of-tokens-loss-scaling ## Overview Language models are trained on sequences of tokens which can be up to “max sequence length” (MSL) in size. To account for smaller sequences of length less than the MSL, inputs can be “padded” to fill the remaining slots in the sequence. The attention mask marks what tokens in an input sequence should contribute to the gradient computation and loss calculations. In autoregressive models like GPT, attention masks also serve to prevent the model from looking at future tokens in an input sequence when predicting a particular output token. The loss of a network during training is a sum over all tokens in the input sequence. To not overweight the loss of larger sequences over smaller sequences, it is important to normalize the final loss by the number of input “non-padded” tokens. This normalization factor is a sum-reduction of the attention mask tensor and we call it `num_tokens`. Instruction fine-tuning and downstream task evaluations are potential use cases for loss scaling by `num_tokens` if the sequences sequences are “unpacked” i.e. each sequence contains one prompt-response pair. Since the attention mask has a batch dimension, in runs with gradient accumulation or on multiple CSX devices, the attention mask will be appropriately reduced over all boxes and gradient accumulation micro-batches. That is, the `num_tokens` value used in the run will correctly reflect the global batch size of the model. ## Procedure Loss scaling by num\_tokens can be enabled within the configuration yaml under the `model` section by changing the `loss_scaling` and `loss_weight` parameters. ```Bash theme={null} model: ... loss_scaling: “num_tokens” loss_weight: 1.0 ``` ## Conclusion Training language models using loss scaling by the number of non-padded tokens (num\_tokens) is essential for handling sequences of varying lengths efficiently. This technique ensures equitable loss contribution from each sequence, irrespective of its length, by normalizing the loss based on active, non-padded tokens. Implementing `num_tokens` in the model’s configuration allows for more accurate and balanced model training, particularly crucial in scenarios with diverse sequence lengths, thereby enhancing the model’s overall performance and robustness. # Release Notes Source: https://training-docs.cerebras.ai/rel-2.5.0/release-notes/release-notes-tabs Stay up to date with the latest features, enhancements, bug fixes, and improvements. ## Release 2.5.0 ### DINOv2 Now Available We've added support for DINOv2, a powerful self-supervised vision model that enables high-quality image representations without labeled data. You can now train and fine-tune DINOv2 models as part of your workflows. Learn more about DINOv2 [here](../../rel-2.5.0/model-zoo/models/vision/dino-v2). ### Fast TTFL and Checkpointing We’ve made major performance improvements to speed up TTFL and checkpointing: | Feature | Model | Time in v2.4 (mins) | Time in v2.5 (mins) | Speedup | | - | - | :-: | :-: | :-: | | **Weight Initialization (i.e., no initial checkpoint)** | **Llama 70B** | 8.5 | 1.25 | 7x | | | **Falcon 180B** | 21 | 5 | 4.2x | | **Checkpoint Loading** | **Llama 70B** | 25 | 1.25 | 20x | | | **Falcon 180B** | 63 (1 hour) | 6 | 10x | | **Checkpoint Saving** | **Llama 70B** | 52 | 1 | 52x | | | **Falcon 180B** | 135 (2.25 hours) | 1.75 | 77x | | **Max Cost of Restart** | **Llama 70B** | 135 (2.25 hours) | 10 | 13.5x | | | **Falcon 180B** | 339 (5.5 hours) | 15 | 22x | ### S3 Checkpointing Save, load, and manage model checkpoints using any S3-compatible storage service. This new capability allows you to persist training progress remotely, share checkpoints across environments, and overcome local storage limitations during large-scale or distributed training, with seamless integration into existing checkpoint workflows. Learn how to enable and setup this feature in [S3 Checkpointing](../../rel-2.5.0/model-zoo/migration/s3-checkpoints). ### Automatic Job Restart Automatic Job Restart enables long-running jobs to automatically recover from intermittent failures, eliminating the need for constant monitoring. This feature tracks job progress using checkpoints while monitoring restart attempts. It automatically flags faulty systems that may have caused failures and restarts from the last saved checkpoint. See the [Automatic Job Restart Guide](../../rel-2.5.0/model-zoo/automatic-job-restart) for complete configuration details and usage instructions. > [!NOTE] > > This feature requires checkpointing to be configured, as restarts will resume from the latest saved checkpoint. ### Job Notifications Now you can configure email, Slack, or PagerDuty notifications in your Trainer YAML file under the backend key when launching training or fine-tuning jobs. For complete setup instructions, see [Configure Notifications](../../rel-2.5.0/fundamentals/job-notifications). > [!NOTE] > > This feature currently supports forwarding error messages only. ### Grafana Dashboards We’ve updated and added new Grafana dashboards for improved cluster and job monitoring. Read more about them [here](../../rel-2.5.0/cluster-monitoring/cerebras-job-scheduling-and-monitoring/cluster-monitoring-with-grafana). > [!NOTE] > > The existing ML Admin and ML User dashboards are still available, but will be deprecated in a later release. ### Data Preprocessing * Now you can preprocess subdirectories within your input directory as separate datasets. You can process each top-level folder, or specify a list of subfolders. Learn more in [Preprocess Subdirectories](../../rel-2.5.0/model-zoo/components/data-preprocessing/input-data-configuration#preprocess-subdirectories). * Now you can stop the data preprocessing pipeline after a specified number of tokens are processed with the token\_limit parameter. Learn more in [Data Handling Params](../../rel-2.5.0/model-zoo/components/data-preprocessing/data-preprocessing#processing-section). * You can now configure dataset preprocessing using flexible split strategies, including by dataset, context length, or both, with support for single or multi-subset directory structures and deterministic random sampling for reproducibility. Learn more in [Dataset Splitting and Preprocessing](../../rel-2.5.0/model-zoo/components/data-preprocessing/data-context-splits). ### Time Estimation for Training and Eval Runs We’re introducing two new metrics in the progress logger that provide more accurate time estimates during model training and evaluation: * `LoopTimeRemaining`: Shows estimated time left in the current operation loop * `TimeRemaining`: Displays estimated time remaining for the entire run Learn more about these metrics in [Launch a Job](../../rel-2.5.0/fundamentals/launch-your-job). ### Model Zoo CLI We no longer recommend using the following Python scripts. This change simplifies workflows by reducing the need to remember complex file paths and provides a more intuitive interface for common tasks. Instead, please use the corresponding [Model Zoo CLI](../../rel-2.5.0/model-zoo/cli-overview) (`cszoo`) commands: | Script | CLI Command | | - | - | | `run.py` | `cszoo fit [args]` | | `convert_checkpoint.py` | `cszoo checkpoint [args]` | | `run_bigcode_eval_harness.py` | `cszoo lm_eval [args]` | | `run_eleuther_eval_harness.py` | `cszoo bigcode_eval [args]` | Additionally, we’ve replaced the `cszoo checkpoint list` command in the Model Zoo CLI with `list-converters`. Now run `cszoo checkpoint list-converters` to view all available checkpoint converters. ### General Improvements * We now support [lm\_eval version 0.4.7](https://github.com/EleutherAI/lm-evaluation-harness/releases/tag/v0.4.7). * We've implemented training time optimizations that deliver faster performance across all supported models. ## Release 2.4.0 We are thrilled to announce Release 2.4.0, delivering substantial performance improvements and expanded capabilities that enhance machine learning model development workflow. This release introduces support for new models, improved mixture of expert capabilities, faster performance, and workflow updates that simplify and streamline the process of training large models. ### Improvements to Model Zoo * **New Model Support:** The latest additions to [Model Zoo](https://github.com/Cerebras/modelzoo/) include Llama 3.3 (70B), Llama 3.2 (1B and 3B), and Mistral NeMO (12B) models. > Note: Please see [this guide](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/data_preparation/data_preprocessing/llama3.3_venv_setup) for instructions on how to conduct data preprocessing for Llama 3.3 70B. * **Extended Max Sequence Length (MSL) Support:** We now support MSL up to 128K tokens for training, fine-tuning, and evaluation tasks. 128K MSL is supported for the following models: * [Mistral NeMO 12B](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/mistral) * [Llama 3.3 70B](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama) * [Llama 3.1 70B](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama) * [Llama 3.1 405B](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama) (Contact your account representative for access.) * [**Model Zoo CLI:**](../model-zoo/cli-overview) Release 2.4.0 introduces a new command-line interface that centralizes all modeling tasks into a single, intuitive tool, allowing users to easily access scripts, utilities, and configuration files for core workflows including data preprocessing, pretraining, fine-tuning, checkpoint conversion, and more. * [**CSZoo Assistant:**](../model-zoo/cli-overview#cszoo-assistant) Introduced a command-line LLM agent that leverages Cerebras Inference to answer questions and execute actions in natural language. Users no longer need to memorize CLI commands or internal workflows—simply ask if features are supported, how to accomplish specific tasks, or request automated command execution for a streamlined and intuitive experience. * [**Config Classes for Streamlined Configuration Management:**](../model-zoo/components/model-zoo-config-classes) Introduced Pydantic-based config classes that provide structured, validated, and immutable schemas for model, data, and training parameters. This approach simplifies customization, ensures data integrity, and enables easier experimentation without requiring deep internal code changes. * [**Streamlined Model Zoo Registry:**](https://training-docs.cerebras.ai/model-zoo/components/model-zoo-registry) Optimized the ModelZoo registry for faster loading, improving startup times and user experience. Users can now register their custom models seamlessly and utilize the CLI to manage them effectively. * **Enhanced Evaluation Framework:** Model Zoo now supports EleutherAI's LM Evaluation Harness (v0.4.5) and the latest BigCode evaluation harness, enabling users to run multiple generative and non-generative evaluation tasks within a single callback. ### Improvements in Data Preprocessing * **Expanded Preprocessing Options**: Introduced both inline and offline preprocessing modes with efficient full-data shuffling, along with multimodal inline preprocessing to support complex, mixed-media datasets. * **Improved Data Handling**: Enhanced file skipping logic and introduced a truncate option (instead of skipping entirely), ensuring users retain maximum usable data. Additionally, a list of skipped files can now be saved for easier review and troubleshooting. * **TokenFlow Enhancements**: Introduced support for Masked Language Modeling (MLM), enhanced the handling of special characters, and refined the user interface to streamline text preprocessing workflows. * **Advanced Text Pretraining Features**: Included semantic region support for text-only pretraining and integrated embedding training data (DPR) for more sophisticated training regimes. * **Data Preprocessing Performance Optimization:** Data preprocessing operations now execute up to 95% faster due to optimized file handling and memory management. These improvements span across various data types and sizes, with processing time reductions of 30-95% across common operations. Users working with both text and multimodal data will experience significantly reduced processing times. ### Enhanced Mixture of Experts Capabilities * **Configurable Expert Selection and Weighting**: Users can now choose both the routing algorithm ("hash" or "learned") and the nonlinearity used for expert selection (Softmax, Sinkhorn, or Sigmoid). The nonlinearity for weighting expert outputs (Softmax or Sigmoid) is also independently configurable, providing greater flexibility and control over the expert routing process. * **Improved Router Regularization**: The router regularization mode can now be toggled between off and load balancing, offering clearer control over distribution of routing choices. * **Null Expert Bias**: Introduced a `null_expert_bias` parameter that represents the model's uncertainty or "none of the above" option when routing. By including a null expert probability in the weighting calculation, gradient flow back to the router is improved, leading to improved loss, especially in scenarios where only the top single expert (`top_k=1`) is selected. Users can continue to choose between normalizing expert weights into a probability distribution or simply using the raw router scores as attention-like weights. The added null expert probability integrates seamlessly with both approaches. * **Shared Experts**: Introduced the ability to designate certain experts as "shared experts" that are always selected for every token, independent of the routing logic. These shared experts are always activated and help capture common knowledge across different contexts. This concept is inspired by [DeepSeekMOE](https://arxiv.org/pdf/2401.06066). ### And More! * **Expanded Cluster Management:** Enhanced support for large-scale deployments now allows operation of clusters with hundreds of nodes, while new upgrade capabilities minimize downtime during maintenance, allowing organizations to maximize both the scale and availability of their compute resources. * **CS-3+ Performance Upgrade:** Enhanced power capabilities on the WSE-3 chip deliver a 1.9x performance improvement over CS-2 systems with linear scaling. This boost benefits all supported models—ranging from 2.7B to 180B parameters—across diverse architectures, vocabularies, context lengths (2k to 128k), and specialized variants like MoE and vLLMs. * **Trillion-Parameter Model Support:** Organizations can now train dense language models at the trillion-parameter scale, reliably running hundreds of iterations on larger clusters and dozens on smaller ones. This milestone maintains training stability and checkpoint functionality, unlocking research and development at unprecedented model sizes. For organizations aiming to train models at the trillion-parameter scale, contact your account representative to discuss the necessary requirements. * **New Docs Platform:** With the release of 2.4.0 we have migrated to a new documentation platform with an improved user interface and AI search feature. Users can now ask questions directly within the search bar and receive LLM-generated, documentation-grounded answers, delivering an intuitive and more interactive experience. ## Release 2.3.1 ### New Model Support ModelZoo now includes several new example reference models, including built-in YAML files for various configurations. Additionally, our checkpoint converter has also been updated to support conversion between HuggingFace and Cerebras formats for these new models, as well as between different Cerebras software releases. * Gemma2 Models in ModelZoo: R2.3.1 introduces support for Gemma 2 9B and 27B models in the ModelZoo. These models can be trained, fine-tuned, and evaluated using multi-CSX clusters, offering competitive performance with expected dense LLM metrics. * Vision Transformer (ViT) Support: This release brings pre-training and fine-tuning capabilities for Vision Transformer models, including ViT Base and ViT Huge. Users can now leverage flexible configurations with various batch sizes, image sizes (from 112x112 to 2048x2048), and patch sizes (8x8, 16x16, 32x32). * Llama 3.1 Models in ModelZoo: Llama 3.1 8B and 70B models are now available in ModelZoo. These models feature updated configs and RoPE scaling changes, maintaining performance parity with Llama 3 models across various context lengths. > [!NOTE] > > We encourage users to use the new YAML config formats. When running the checkpoint conversion tool to upgrade from previous releases to release 2.3.1, the converted config is in the new YAML format. ### Key Enhancements Improved TensorBoard event file logging: Event files have been consolidated into a single subdirectory, streamlining organization and access. This change, implemented based on user feedback, offer a more intuitive and efficient logging structure compared to the previous grouped format. ## Release 2.3.0 ## New Model Support ### Beta Support for Mixture of Experts (MoE) Release 2.3.0 now supports Mixture of Experts (MoE) models in Model Zoo. This new feature allows for significantly higher quality and faster inferencing in various AI applications. MoE models leverage a mixture of specialized expert networks to improve performance and efficiency, particularly in large-scale text generation and other complex tasks. This update ensures that users can take advantage of state-of-the-art (SOTA) techniques to enhance their AI models’ capabilities and outputs. ### New Model Zoo Models We are excited to announce the following models with training scripts and configuration files have been added to Model Zoo: * [Mixtral 8x7B and 8x22B](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/mixtral/): Mistral AI’s latest Mixtral models are now available as a Beta feature. Mixtral models incorporate Sparse Mixture of Experts (SMoE) for significantly higher quality and faster inferencing in text generation. * [Multimodal Simple](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/multimodal/multimodal_simple/): A new model enhancing multimodal capabilities for processing multiple images intermingled with text, significantly improving model flexibility and performance. This release also includes improved checkpoint conversion scripts. * [ESM-2](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/esm2/) and [ESM-2 Classification](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/esm2/classification/): ESM-2 (Evolutionary Scale Modeling 2) is a SOTA model trained on a masked language modeling objective for predicting protein sequences. This release also includes ESM Classification, a specialized model for predicting if a given protein sequence lives inside or outside a cell, as well as other protein functions and characteristics. ## Key Enhancements ### Enhanced API for Training and Validation Release 2.3.0 introduces an entirely new and improved API for training and validating models through Cerebras Model Zoo. Through the new [Trainer class](../model-zoo/trainer-overview) and a new [YAML configuration format](../model-zoo/trainer-configuration-overview), you can now do complex training and validation runs and easily customize the behavior. Some notable new capabilities enabled through this new workflow include: * Ability to run [upstream pretraining](../model-zoo/core-workflows/pretraining-with-upstream-validation) and downstream validation (through [Eleuther Evaluation Harness](../model-zoo/core-workflows/downstream-validation-using-eleuther-eval-harness) and [BigCode Evaluation Harness](../model-zoo/core-workflows/downstream-validation-using-bigcode-eval-harness)) interleaved with training. * Ability to specify and run hyperparameter scheduling all from a single YAML configuration. * Ability to combine a [multi-phase training](../model-zoo/core-workflows/multi-phase-training) with different batch sizes or max sequence lengths in a single config file or python script. * Ability to extend the Trainer functionality through [callbacks](../model-zoo/components/trainer-components/customizing-the-trainer-with-callbacks), all specifiable within the new YAML configuration format. Callbacks allow you to inject functionality into the Trainer to modify the training loop as you see fit. This enables adding Alerts or writing custom stopping criteria that fit your needs. * Ability to flexibly configure [checkpoint](../model-zoo/components/trainer-components/checkpointing) management with auto-cleanup policies, customize the loading behavior, and more. ### Improved Data Preprocessing framework In Release 2.3.0, we have significantly enhanced our [data preprocessing](../model-zoo/components/data-preprocessing/data-preprocessing) framework to be more flexible and extensible. * Ability to easily format their [input dataset](../model-zoo/components/data-preprocessing/input-data-configuration) (for prompt-completion, or chat-style datasets) using [pre-built hooks](../model-zoo/components/data-preprocessing/input-data-configuration) or by [writing custom hooks](../model-zoo/components/data-preprocessing/read-hooks). * Ability to create [custom tokenizers](../model-zoo/components/data-preprocessing/custom-tokenizer) and [token generators](../model-zoo/components/data-preprocessing/token-generators) to preprocess data for a variety of training objectives and new models. * We have expanded our capabilities to preprocess datasets from Hugging Face, while still supporting local datasets as in previous versions. * Ability to easily preprocess [Hugging Face datasets](../model-zoo/components/data-preprocessing/online-shuffling-in-hdf5-file-storage). ### Enhanced μP Configuration Interface Release 2.3.0 introduces a new interface for [configuring models](../model-zoo/tutorials/training-an-llm-using-maximal-update-parameterization/configure-mp-for-gpt-style-models) in μP (Maximal Update Parametrization) through Model Zoo. μP is a technique that enables faster and more stable training of large models by adjusting how different parts of the network are updated during learning. Notable changes to the way we handle and support μP include: * Beta support for three new models: GPTJ, BERT Pretrain, and T5. * The ability to specify the dimensions of the proxy model in the parameters of the target model for automatic initializer, weight, and learning rate scaling. * Additional tunable hyperparameters designed to assist with stabilizing output and attention logits. * Finer-grain control of layer-specific learning rate scaling through the addition of supported learning rate adjustment groups in μP models. * Backward compatibility with previous μP configurations, along with checkpoint and configuration conversion tools to update your models to the new interface. ### Config Class improvements All new models, including multimodal models, now have [config classes](../model-zoo/components/model-zoo-config-classes). Config classes help prevent errors and make code easier to manage by defining expected data types and constraints, providing a clear and organized way to handle configuration settings. ### Performance Boost GPT Models In Release 2.3.0, we’ve increased model FLOPs utilization (MFU) for GPT class models like [LLaMA](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/llama/) and [JAIS](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/jais/) with extended sequence lengths. MFU is the best way to measure LLM training efficiency, and looks at how much of the maximum possible computing power is used for only the necessary training tasks. These models now experience: Experience a significant performance enhancement for GPT class models with extended sequence lengths. * 3% improvement in MFU and training time for 32K Maximum Sequence Length (MSL) * 8% improvement in MFU and training time for 128K Maximum Sequence Length (MSL) ### CBfloat16 (CB16) support for Input Activations and Multimodal models The CB16 data format significantly accelerates model performance on the Cerebras platform. In R2.3.0, CB16 can be used for input activations, enabling cb16 for multimodal models like LlaVa 1.5. ### Flexible Batch Size configuration In version 2.3.0, users can now specify an arbitrary global batch size without needing it to be divisible by the number of systems in a multi-system training run. Our platform automatically selects appropriate micro-batch sizes to ensure an even distribution across CS-X systems, eliminating the need to change the global batch size when scaling the number of systems up or down. Note that while batch sizes are no longer constrained, certain values can still result in low samples/second performance. Click [here](../model-zoo/tutorials/optimize-performance-with-automatic-microbatching) to learn more! ## Release 2.2.1 ### New general features * In Release 2.2.1, we now support **Train and Eval** - a new workflow mode that will automatically switch between training and evaluation modes within the same process, to enable period validation during training runs. This means you no longer need to start and stop a run on the CSX cluster to switch between train and eval jobs, improving workflow efficiency and optimizing system utilization. Click [here](../model-zoo/tutorials/training-and-fine-tuning-a-large-language-model--llm#validating-during-training) for details on how to configure Train and Eval. * Llama 3 is now in the Model Zoo: Meta’s latest **Llama 3 model is now available in the Cerebras Model Zoo** as a reference in both 8B and 70B configurations, ensuring continuity of work for users interested in switching to the latest and greatest. Llama 3 runs at comparable-to-better performance on the Cerebras platform, compared to Llama 2. To access Llama models in the Model Zoo, click [here](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/llama/). * Release 2.2.1 now includes support for the Dense Passage Retriever (DPR) on CS-X, which uses separate encoders for questions and passages to improve search results in large datasets. This is particularly useful for building intelligent virtual assistants! Please visit the link to our [DPR model](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/dpr/) for a reference implementation and YAML config files. * In Release 2.2.1, we introduced our new chunk-based data preprocessor that maximizes CPU utilization through concurrent processing in the pipeline and ensures fault tolerance with a checkpoint system for recovery. It also offers a real-time progress bar and detailed logging for continuous performance tracking. ## Release 2.2.0 ### New general features * The **Cerebras CS-3** is officially released, featuring the WSE-3, offering up to 2x faster performance! R2.2 ensures enhanced efficiency and compatibility with key models like GPT-2, GPT-3, LLaMA, and more, all rigorously tested for peak performance, with reference examples provided in our [Cerebras Model Zoo](https://github.com/Cerebras/modelzoo). * Release 2.2.0 delivers significant **usability improvements to the Cerebras Model Zoo**. Model Zoo now supports config classes for easy management of model configuration and automatic validation of YAML inputs, introduces clearer directory organization, new model registry APIs, and enhanced NLP data preprocessing tools for more efficient ML development and experimentation. Learn about our [Model Zoo improvements](../model-zoo/model-zoo-overview). * **Note on breaking changes in restructured Model Zoo** - The directory restructuring introduces backwards-incompatible changes to Cerebras package imports. Please make sure to make the following changes to your files:| Previous import | New import | \| --------------------------- | ------------------------------------ | \| `import cerebras_appliance` | `import cerebras.appliance` | \| `import cerebras_pytorch` | `import cerebras.pytorch as cstorch` | \| `from modelzoo import` | `from cerebras.modelzoo import` | * Release 2.2.0 introduces support for **EleutherAI’s Evaluation Harness (EEH) version v0.4.0**. Learn about our supported EEH tasks. ### New GenAI features * Introducing **Multimodal support**, enabling Visual Question & Answering use cases. In the Cerebras Model Zoo, we provide a reference [Multimodal LLaVA model](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/multimodal/llava) architecture with CLIP-ViT and Vicuna encoders, offering flexible backbone replacement and layer freezing in training, alongside 7B and 13B configs, checkpoint converters, and extensive dataset support for Pretraining and Instruction finetuning. For more information on Cerebras checkpoints released on Hugging Face, click [here](https://huggingface.co/collections/cerebras/cerebras-llava-65f9c3cda9205f7264787911). * Release 2.2.0 delivers **higher-performance Sliding Window Attention (SWA)** support (Child et al., Beltagy et al.), an approach which allows models to handle longer sequences at lower compute cost. In R2.2.0, models using SWA like Mistral 7B-32k can experience performance improvements of 57%. You can see an example of SWA being used in Mistral 7B [here](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/mistral/configs/params_mistral_7B.yaml) in the Model Zoo. * Introducing **Position Interpolation** for models using RoPE. Position interpolation enables pre-trained LLMs to process longer context windows beyond their original pre-trained lengths, while preserving quality on the original context length. This significantly reduces computational load and training time, while increasing task flexibility. Learn more about how to work with Position Interpolation here. * The Cerebras data preprocessing tool now officially supports **dataset processing for Direct Preference Optimization (DPO)** datasets. Learn more here. ### Sparsity * The **Sparsity API has been revamped for greater clarity and usability**. The keys to specify sparsity in the YAML configuration have changed. For more information, refer to [Sparsifying models](../model-zoo/tutorials/train-a-model-with-weight-sparsity). ### Key API & behavior changes * `max_checkpoints` **is now stateless** across multiple invocations of `run.py`. This means that checkpoints generated by a previous run in the same `model_dir` will no longer be counted towards `max_checkpoints` for the current run, and that the previous checkpoints will **no longer be automatically deleted** in the current run. This provides you with greater flexibility to control which checkpoints are deleted vs. saved from run to run, but also means you may want to keep a closer eye on remaining disk space. * The `use_cs_grad_accum` **YAML parameter in Model Zoo models has been deprecated** and no longer needs to be explicitly configured to work with gradient accumulation. To set specific micro batch sizes and enable or disable gradient accumulation, you should now directly set the `micro_batch_size` YAML parameter to none | auto | explore | \. See page working\_with\_microbatches for details. * **Specifying** `micro_batch_size` **when constructing a** `cstorch.backend` **is now deprecated**. To specify `micro_batch_size` using the cstorch API, pass this option to `cstorch.utils.data.DataExecutor` instead. This change gives users the ability to choose different micro batch sizes for train vs. eval tasks. * In Release 2.1.0, the directory structure of some files under `model_dir` has changed. There are now subdirectories for each individual run with their own artifacts. These subdirectories are named `model_dir/cerebras_logs//`. Checkpoints, Tensorboard event files, and YAMLs still exist directly under `model_dir`. The most recent run’s subdirectory can be accessed using the symlink - `model_dir/cerebras_logs/latest`. Run logs have been moved from `model_dir/run_xxx.log` to:`model_dir/cerebras_logs///run.log`or`model_dir/cerebras_logs/latest/run.log` ### Known Issues * Release 2.2.0 temporarily introduces an issue with **training models using context lengths longer than 32K**. This is being actively worked on and will be fixed in an upcoming patch release. * In Release 2.2.0, **the automatic kernel generation feature (Autogen) is temporarily unavailable**. If your model previously required autogen and is now no longer compiling, reach out to the Cerebras Support Team for assistance. We will be restoring autogen functionality in a future release. Release 2.1.1 * In Release 2.1.0, a behavior was introduced where, if the user did not specify the `max_checkpoints` parameter in the runconfig portion of the yaml config file, it would default to 5 and only retain the 5 most recent checkpoints. In release 2.1.1, `max_checkpoints` now defaults again to infinity, reverting back to previous default checkpoint saving behavior. * In Release 2.1.1, the automatic kernel generation feature (autogen) is temporarily unavailable. Make sure that in your runconfig file, you set `autogen_policy:disabled` if you were previously using it (for more information on how to do this, click on [Autogenerating fused kernels for loss operations](../fundamentals/kernel-autogeneration-with-autogen#autogenerating-fused-kernels-for-loss-operations)). If your model previously required autogen and is now no longer compiling, reach out to the Cerebras Support Team for assistance. We will be restoring autogen functionality in the next release. ## Release 2.1.0 Release 2.1.0 introduces minor changes to transformers model implementations and runner API in Model Zoo. To ensure seamless migration from 2.0.2, a checkpoint and model YAML configuration must be “converted” to become compatible with Release 2.1.0. For more information, refer to [Upgrading Checkpoints From Previous Versions](../model-zoo/migration/convert-checkpoints-and-model-configs/convert-checkpoints-and-model-configs). ### New features and Enhancements #### General Features * We optimized weight-initialization, step leading to a 25% reduction in time to the first loss - time from launching a training job till the first loss appears in the logs. This speed-up is an outcome of [Lazy Weight Initialization](../cs-torch/writing-a-custom-training-loop/efficient-weight-initialization), a new feature that enables tracing a model’s initialization. Lazy initialization allows us to defer initializing the weights to when it is optimal. At the moment, it’s being deferred so that weight initialization happens in parallel with compilation. * We now offer training with [Per-layer Precision Optimization Levels (POL)](../cs-torch/writing-a-custom-training-loop/per-layer-precision-optimization-level) in the Cerebras Wafer-Scale cluster. This feature empowers fine-grained precision control for each layer, enhancing convergence stability and mitigating numerical instabilities inherent in low-precision kernel data types. * We updated the Cerebras-tailored Grafana dashboards to provide ML Admins with an overall usage of the cluster and to provide ML users with detailed information about their jobs. The dashboard queries were updated to support large-scale clusters and jobs better. #### Large Language Models * Release 2.1.0 improves training speed for autoregressive decoder-only transformers by up to 20% by leveraging the custom Cerebras 16-bit floating point format `cbfloat`. Training jobs can be switched seamlessly from `bfloat` to `cbfloat` with dynamic loss scaling without impact on model accuracy. For more information, refer to our documentation on [Numerical Precision Level](../model-zoo/components/trainer-components/numeric-precision). * Release 2.1.0 introduces dynamic loss scaling for `cbfloat16` training. When initializing from `bfloat` checkpoints from past releases without loss scaling, explicitly specify `--load_checkpoint_states` or its `runconfig` equivalent to ensure parameter loading from `params.yaml`. Subsequent checkpoints will inherit dynamic loss scaling and not require this. * We introduce automatic batch exploration for large language models to help users find the throughput-optimal micro-batch size seamlessly. * Release 2.1.0 includes support for running non-generative (non-autoregressive) evaluation tasks in Eleuther AI’s Evaluation Harness (EEH) on the Cerebras Wafer-Scale cluster. The supported EEH version is v0.3.0. Supported Model Zoo models are GPT2, GPT3, BTLM, BLOOM, LLaMA, Mistral, MPT, StarCoder, and SantaCoder on CS-2. * Release 2.1.0 introduces [Map and Iterable dataloaders](../cs-torch/writing-a-custom-training-loop/restartable-dataloaders) for large language models in Model Zoo, enhancing training workflow efficiency. * Cerebras now enables direct HDF5 generation from raw sources, streamlining workflow efficiency and enabling unparalleled control over data format and granularity. Check out our detailed guide to learn about the process. #### Sparsity * In release 2.1.0, we introduce [Sparse Iso-FLOP Transformations for Maximizing Training Efficiency](https://arxiv.org/abs/2303.11525), a technique designed to improve model quality over dense without increasing training FLOPs. To get started with Sparse-IFT, we have provided a comprehensive Sparsity how-to-guide. Additionally, you can explore reference configurations in the Model Zoo to leverage it effectively in your projects. The Model Zoo reference configuration is accessible [SPDF Model Zoo configuration](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/gpt3/configs/sparsity/pretraining). For more information, you can read our [blog](https://www.cerebras.net/blog/can-sparsity-make-ai-models-more-accurate) or contact the support team. ### Other features * In Release 2.1.0, the directory structure of some files under `model_dir` have changed. There are now subdirectories for each individual run with their own artifacts. These subdirectories are named `model_dir/cerebras_logs//`. Checkpoints, Tensorboard event files, and YAMLs still exist directly under `model_dir`. The most recent run’s subdirectory can be accessed using the symlink - `model_dir/cerebras_logs/latest`. Run logs have been moved from `model_dir/run_xxx.log` to:`model_dir/cerebras_logs///run.log`or`model_dir/cerebras_logs/latest/run.log` ### Known Issues * If a run is terminated mid-execution, temporary debug artifacts may accumulate excess storage space. Users should manually clear the `model_dir/cerebras_logs` data when safe to delete if no longer necessary for debugging. * Automatic batch exploration support is limited to LLM networks. A runtime error will be issued if you attempt to use automatic batch exploration with computer vision networks. ## Release 2.0.2 ### New features and enhancements #### Cerebras Software * Cerebras now supports PyTorch version 2.0 and we have released a new [Cerebras PyTorch 2.0 API](../cs-torch/cerebras-pytorch-api). This helps us continue to improve the usability and generalizability of our software stack and ability to support the latest advancements in PyTorch. Users no longer have to install the custom PyTorch wheel as part of Cerebras software setup. * The `experimental_api` flag within the `runconfig` portion of model configuration YAML files is deprecated with the official release of the Cerebras PyTorch 2.0 API. * All Model Zoo models now use the new [Cerebras PyTorch 2.0 API](../cs-torch/cerebras-pytorch-api). Users will not notice a change to the configuration YAML and `run.py` workflow, but now users can also write their own training loops and make other customizations. See more information on how to [write your own training loop](../cs-torch/writing-a-custom-training-loop). * When writing custom models, note that optimizers and learning rate schedulers have been moved into `cerberas_pytorch`. See documentation [here](../cs-torch/writing-a-custom-training-loop) for details. Losses and layer implementations from the layers API still remain in the Cerebras Model Zoo. For more information, contact our support team. * We improved deterministic restart of custom dataloaders with the new Cerebras PyTorch API. Refer to our [documentation](../cs-torch/writing-a-custom-training-loop/restartable-dataloaders) to see how to save and load the dataloader state along with existing mechanisms for saving model checkpoints during a training run. #### Sparsity * With release 2.0.2, we introduce [Sparse Pretraining and Dense Finetuning (SPDF)](https://arxiv.org/abs/2303.10464), a technique designed to accelerate pretraining by incorporating high levels of sparsity while maintaining downstream task accuracy through dense finetuning. To get started with SPDF, we have provided a comprehensive Sparsity how-to-guide. Additionally, you can explore reference configurations in the Model Zoo to leverage SPDF effectively in your projects. Click here for [SPDF Model Zoo configuration](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/gpt3/configs/sparsity). * With release 2.0.2, we introduce [Sparse Pretraining and Dense Finetuning (SPDF)](https://arxiv.org/abs/2303.10464), a technique designed to accelerate pretraining by incorporating high levels of sparsity while maintaining downstream task accuracy through dense finetuning. To get started with SPDF, we have provided a comprehensive Sparsity how-to-guide. Additionally, you can explore reference configurations in the Model Zoo to leverage SPDF effectively in your projects. Click here for [SPDF Model Zoo configuration](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo//models/nlp/gpt3/configs/sparsity). #### Large Language Models * Cerebras released [Bit Tensor Language Model(BTLM)](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/btlm), the best performing and the most downloaded 3B model in the world, in July. G42, a Cerebras strategic partner, released the #1 Arabic language model in the world, **Jais**, in September. Both models used high-performing architectures ([Maximal Update Parameterization (μP)](https://arxiv.org/abs/2203.03466), [SwiGLU](https://arxiv.org/abs/2002.05202) activations, [ALiBi](https://arxiv.org/abs/2108.12409) position encodings). More details can be found in in the [BTLM](https://arxiv.org/abs//2309.11568) paper. * Both static and dynamic weight sparsity are supported in release 2.0.2 for [faster training](https://www.cerebras.net/blog/harnessing-the-power-of-sparsity-for-large-gpt-ai-models) and [higher accuracy](https://www.cerebras.net/blog/can-sparsity-make-ai-models-more-accurate). We provide example sparse model configurations in the Cerebras Model Zoo. For more information, refer to our sparsity how-to-guide. * GPT style models train with approximately 50% improved performance in release 2.0.2. * [LLaMa 7B, 13B, 70B](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/llama) is supported for training from scratch, continuous pretraining, or fine-tuning from a pretrained checkpoint. * [Falcon 40B](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/falcon) is supported for training from scratch, continuous pretraining, or fine-tuning from a pretrained checkpoint. * [StarCoder 15B](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/nlp/starcoder) is supported for training from scratch, continuous pretraining, or fine-tuning from a pretrained checkpoint. * The default dataloader for GPT-style models is now GptHDF5MapDataProcessor. #### Computer Vision Models * Added support for the [Diffusion Transformer(DIT)](https://arxiv.org/abs/2212.09748). Our [DiT](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/vision/dit) model supports AdaLN conditioning and the following model sizes: Small, Base, Large, XL, 2B. Diffusion Transformer also supports multiple patch-sizes like /2, /4, and /8 and image sizes up to 512 x 512. ### Other features * We have deprecated old PyTorch BaseModel and BaseRunner classes as part of our update to PyTorch 2.0. Check out our latest [Cerebras PyTorch 2.0 API](../cs-torch/cerebras-pytorch-api). * Enabling gradient accumulation now makes the stack search for a micro-batch size that provides good training throughput performance. This makes compile times longer. Users may avoid this compile time by supplying a micro-batch size with the `micro_batch_size` parameter within the `train_input` and `eval_input` sections of the model configuration YAML. Note that `batch_size/num_csx` must be a multiple of `micro_batch_size`. Micro-batch sizes with good performance are recommended within the gradient accumulation Micro-batch size setting in YAML params within the Cerebras Developer Documentation. * Distributed data parallel model evaluation is now supported on multiple CS-2 systems in a Wafer-Scale cluster. * Previous limitations in T5 compile times have been addressed. T5 XXL compile time is now less than 90 minutes with a specified micro-batch size. * Jobs submitted from the user nodes to the Wafer-Scale Cluster now include a token that identifies the user submitting the job. This token can be validated on the appliance cluster for user authentication. This change is made to improve security. Machine learning users will not notice any difference in their workflows. * We improved messages related to job scheduling errors to provide clear guidance for users to take corrective action. * Loss scaling by number of tokens is supported on single box and multi-box, with and without gradient accumulation. See our documentation. * The `is_pretrained_checkpoint` flag has been deprecated for clarity. Users should instead use the `load_checkpoint_states` in conjunction with `checkpoint_path` to specify which components are loaded from the checkpoint. Allowed values are `model`, `optimizer`, `dataloader`, `grad_scaler`, `lr_scheduler`. For more information, see the PyTorch params documentation. * Model checkpoints in 2.0 have a new format. When converting checkpoints from pre-2.0 releases to release 2.0+, refer to the fix\_checkpoints\_prior\_releases page in addition to the [Convert checkpoints and model configs](../model-zoo/migration/convert-checkpoints-and-model-configs/convert-checkpoints-and-model-configs). ### Known Issues * [DIT](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/models/vision/dit) supports up to 1k by 1k image sizes, but compile time for this input size is extremely long. * We encourage users to save models and artifacts (with model\_dir) on fast storage (SSD backed, local or NFS) to achieve significant improvement in weight initialization, checkpoint loading, and sending weights from host to wafer when using cached compilation. * Using larger batch sizes provides better training performance but increases compile times. * Dynamic sparsity cannot be used with gradient accumulation (`use_cs_grad_accum` in `runconfig` of YAML) in release 2.0.2. * Computer vision workloads (UNet and ResNet) will cause out of memory errors if scheduled in parallel with other jobs on the appliance. * Hugging Face’s Transformers library does not support Maximal Update Parameterization (muP) or models with SwiGLU and ALiBi. If you have a Cerebras GPT2/3 checkpoint that uses muP, it is possible to convert it to the GPT2 Hugging Face model to perform inference. Custom models can still be used with Hugging Face via the Hugging Face Hub. * Gradient accumulation for computer vision models is supported by the software stack but has not been fully tested across all model variants. We plan to perform comprehensive qualification testing for CV models with gradient accumulation as part of the upcoming 2.1 release. This will ensure that larger batch sizes can be confidently utilized for your computer vision tasks. * The number of heads `num_heads` within a transformer block should not be a prime number. ## Release 2.0.0 and 2.0.1 > [!NOTE] > > Note > > 2.0.0 and 2.0.1 were our special, small-distribution releases. 2.0.2 is our general release. ## Release 1.9.2 ### Other features * This release contains a patch fix for security vulnerability [CVE-2023-4911](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-4911). For RockyLinux it is covered by [this patch](https://errata.rockylinux.org/RLSA-2023:5455). The release contains the package and script required to deploy this security vulnerability patch. ## Release 1.9.1 ### New features and enhancements #### Large Language Models * Maximal Update Parameterization (muP), used for improving training stability and transferring hyperparameters from smaller language models to Larger Language Models (including CerebrasGPT), is now available for GPT-2 and GPT-3 style models. See the How-to guide for usage. * New checkpoint converters between Hugging Face and Cerebras formats have been added. See more at ../port/porting-checkpoints. * Gradient accumulation is enabled for all transformer language models in 1.9.1 through YAML config. * Pre-trained [Falcon 7B](https://github.com/Cerebras/modelzoo/tree/main/modelzoo/models/nlp/falcon) is supported in Model Zoo. * Pre-trained [LLaMA 7B, 13B, and 33B](https://github.com/Cerebras/modelzoo/tree/main/modelzoo/models/nlp/llama) are supported in Model Zoo. * [BLOOM 7B](https://github.com/Cerebras/modelzoo/tree/main/modelzoo/models/nlp/bloom) is available in Model Zoo. ALiBi positional encodings can be enabled in all GPT-style models through the `model` section in the configuration yaml. ```Bash theme={null} position_embedding_type: 'alibi' alibi_trainable_slopes: False # whether the slopes of the alibi embedding is trainable (default to False). alibi_implementation: 'expand' # We support `embedding` and `expand` with default set to `expand`. ``` #### Computer vision models * Fixed bugs and improved performance for computer vision models. ### Other features * Improved stdout messages. Added console progress bars to provide more detail about the operations on the Wafer Scale Cluster. * Improved tooling for cluster resource management, job monitoring, and performance monitoring. For more information, see ../getting-started/csctl. * Pipeline mode and TensorFlow support is deprecated in 1.9.1. All models must use PyTorch and weight streaming functionality. There is no longer a need to specify a `{pipelined,weight_streaming}` argument in `run.py` because all models will run in `weight_streaming` mode by default. All models previously supported in Pipeline are now supported for Weight Streaming. * The `batch_size` parameter in Model Zoo `yaml` configuration files now represents the total effective batch size of the model and is divided evenly across the specified `num_csx` CSX systems. This differs from pre-1.9.0 behavior, where the `batch size` parameter defined the batch size per CSX, not globally. Note that `batch_size` must now be divisible by `num_csx`. * Custom worker containers are enabled by default, allowing user environment to be replicated into the worker servers running inside the appliance. The deployment/admin user needs to specify the cluster volume that can be used for virtual environment copy. This feature can also be turned off during deployment if needed. ### Known Issues * Some dataloader implementations from Model Zoo require evaluation to be done on a single CS-2 rather than multiple CS-2s. Multibox evaluation has no explicit limitation, but these dataloaders require the dataset to be sharded in such a way that each worker gets at least one file. Evaluation datasets are often small and not split into many files. * All T5 limitations from Release 1.8 remain. * Loss scaling by number of tokens (`num_tokens`) is not yet fully supported and requires coordination with the Cerebras team. * GPT NeoX suffers NaNs when trained with extremely long sequence lengths (30k, 50k). * The base, pre-trained Falcon and LLaMA variants are supported. Other variants, such as those with long sequence lengths or different numbers of heads, may not be supported. * Running several jobs in parallel with the same `model_dir` can cause issues. ## Release 1.9.0 > [!NOTE] > > Note > > 1.9.0 was a special, small-distribution release. 1.9.1 is our general release. ## Release 1.8.0 ### New features and enhancements #### Large language models * Added support for **T5 models up to 11B parameters** with Weight Streaming execution mode. T5 is supported **with source and target inputs up to 2K tokens**. * Added support for **BERT pre-training** with Weight Streaming execution mode. BERT is supported **with input sequences up to 30K tokens**. * Added support for gradient accumulation for GPT-style and BERT-style language models, allowing for larger effective batch sizes. See gradient\_accumulation for more details. * Added support for deterministic checkpointing of dataloaders for language models to enable pausing and restarting of training runs without using duplicate samples or batches. See dataloader\_restart for more details. * In past releases pre-layer normalization in our T5 & Transformer models required setting `use_pre_encoder_decoder_layer_norm: False`. This was confusing, and we have changed the behavior in 1.8. To enable pre-layer normalization you should instead set `use_pre_encoder_decoder_layer_norm: True`. This update better aligns the naming of the parameter to its usage. To use release 1.7 checkpoints in release 1.8, you’ll need to update the config to reflect this change. Directions for converting configuration files can be found in our [checkpoint conversion documentation](../model-zoo/migration/convert-checkpoints-and-model-configs/convert-checkpoints-and-model-configs). * You may now control the activation function used by the BERT pooler (`pooler_nonlinearity`) and masked language model head (`mlm_nonlinearity`) independently of the activation used for the rest of the model (`encoder_nonlinearity`). Both will default to `encoder_nonlinearity` if not explicitly set. Use the [checkpoint conversion documentation](../model-zoo/migration/convert-checkpoints-and-model-configs/convert-checkpoints-and-model-configs) to convert 1.7 configuration files to 1.8 to have access to this feature. #### Computer vision models * Added support for 3D UNet model in Weight Streaming execution to enable segmentation of large volumes of up to 512 x 512 x 160 pixels. Single CS-2 system support only. Check our reference implementation and learn more in the [Model Zoo](https://github.com/Cerebras/modelzoo/tree/main/src/cerebras/modelzoo/vision/pytorch/unet#u-net-3d-model). * Multi-channel multi-class segmentation is now supported for 2D UNet. * 2D UNet now supports image sizes up to 7k x 7k * Improved 2D CNN robustness & support, for example ResNet 2D on up to 1k x 1k images * 2D UNet now runs at high performance on 256 x 256 resolution ### Other features[#](#id20 "Permalink to this headline") * We are releasing scripts and instrucions for checkpoint and configuration conversion to and from corresponding Hugging Face models and between Cerebras software versions. More details in [Convert checkpoints and model configs](../model-zoo/migration/convert-checkpoints-and-model-configs/convert-checkpoints-and-model-configs). * Added support for `eval_all` and `train_and_eval` to enable users to evaluate models throughout long training runs or evaluate all checkpoints after training has completed. Mode details in eval. * The Cerebras Model Zoo run scripts have been updated with a more informative and explicit command line interface. For more details please read [Launch your job](../fundamentals/launch-your-job). * The script `run_appliance.py` has now been deprecated for TensorFlow in favour of one single script called `run.py` that employs the aforementioned run script changes. * More custom losses and non-linearities are now supported with AutoGen feature. It allows users to swap operations (losses, nonlinearities, positional encodings) for language models and improves performance of loss functions with fused kernels. Learn more about [Kernel autogeneration with AutoGen](../fundamentals/kernel-autogeneration-with-autogen). * You can now use scalar and tensor summaries in PyTorch to track various tensors of interest during training. Internally we heavily rely on these features for example to track parameters like gradient norms during training of large language models. Learn mode about how to model-summaries. ### Known Issues * T5 with input or output sequences longer than 1024 tokens (`src_max_sequence_length` and `tgt_max_sequence_length` parameters in model yaml config file) may have compile times of over 3 hours. T5 is only supported with input and output sequences up to 2048 tokens. * T5 has limitations with respect to gradient accumulation and batch sizes (BS). * Gradient accumulation is not supported for T5. * At [precision optimization level](../model-zoo/api/trainer-api) 0 (POL0), the largest supported batch size for T5 model with 11B parameters is 220. * At precision optimization levels 1 and 2 (POL1 and POL2) batch sizes over 770 for T5 3B and over 260 for T5 11B will result in a long compile time. * Models will not compile if `(vocabulary V / (heads * Greatest_Common_Divisor(Sin, Sout)) > 2^11`. * Maximum supported vocabulary size for language models is 1 million. * Downloading data sets from the internet within data loaders is not supported. As a workaround, please download data sets and prepare them outside the dataloader function. See [PyTorch FC MNIST implementation](https://github.com/Cerebras/modelzoo/blob/main/modelzoo/fc_mnist/pytorch/prepare_data.py) for an example and additional details. * Users creating their own models and training scripts must separate the dataloader or input\_fn into a separate Python file from the rest of the training script, in order to avoid the error described [here](../support/troubleshooting/error-receiving-activation). * The experimental PyTorch API does not save checkpoints at steps 0 and 1 in the correct format. No issues with checkpoints at other steps or outside the experimental API. * When `share_embedding_weights` parameter is set to `True` for PyTorch GPT-style models (e.g. [here](https://github.com/Cerebras/modelzoo/blob/main/modelzoo/models/nlp/gpt3/configs/Cerebras_GPT/111m.yaml#L43#L43)), custom settings for `embedding_initializer` in the yaml configuration (like [here](https://github.com/Cerebras/modelzoo/blob/main/modelzoo/models/nlp/gpt3/configs/Cerebras_GPT/111m.yaml#L43#L66)), are ignored. Embedding weights are initialized with default configuration (normal distribution, std=0.02). This is done by the `__rest_parameters` [function](https://github.com/Cerebras/modelzoo/blob/main/modelzoo/models/nlp/gpt2/gpt2_model.py#L180), which is called at the end of the [GPT2LMHeadModel initialization](https://github.com/Cerebras/modelzoo/blob/main/modelzoo/models/nlp/gpt2/gpt2_model.py#L173) ## Release 1.7.1 ### New features and enhancements #### Unified user workflow on the Wafer-Scale Cluster * User workflow on the Wafer-Scale Cluster is now the same for Pipelined and Weight Streaming execution. The same launching scripts and the same environment can now be used to run larger models with Weight Streaming execution and smaller models with Pipelined execution. Use additional command line argument with `run.py` for PyTorch and with `run_appliance.py` for Tensorflow: set `--execution_strategy` argument to `pipeline` or `weight_streaming` to specify execution mode. * Note that Pipelined execution only supports using one CS-2 for each run. It is only valid to specify `--num_csx=1` in the run command for Pipelined execution. Weight Streaming does not have such requirement. ### Known issues #### Specifying number of workers * `--num_workers_per_csx` denotes the maximum number of Kubernetes worker pods per CS-X. Note that these are distributed across physical worker nodes attached to each CS-X on the Wafer-Scale Cluster. * For this release, please specify `--num_workers_per_csx=8` as a command line argument in the run command for Pipelined execution. Weight Streaming execution does not need to specify this argument. #### Specifying path in the configuration file * Please specify absolute paths for any configuration parameters that are used by dataloaders in PyTorch or the input\_fn in TensorFlow. More specifically, this applies to all variables in `train_input` and/or `eval_input` sections of the configuration yamls. #### Padding token in loss calculation * TensorFlow BERT fine-tuning token classification model does not support padding tokens in loss on the Wafer-Scale Cluster for both Pipelined and Weight Streaming execution. Please set `include_padding_in_loss: False` in the configuration yaml. We believe it makes the most sense to exclude padding tokens in the loss calculation. Such setting differs from the original public implementation where token padding is included in the loss, which is most likely used for performance optimization on GPUs, leading to our eval accuracy being potentially different from published numbers. This does not apply to the PyTorch version or the Original Cerebras Installation. #### TensorFlow BERT SQuAD Unsupported * TensorFlow BERT fine-tuning model for SQuAD is not supported in appliance (neither Pipelined nor Weight Streaming). If you would like to fine-tune BERT with SQuAD, please use the PyTorch version. ## Release 1.7.0 ### New features and enhancements #### Large language models * Added support for GPT-J-style models up to 20B parameters in PyTorch, e.g. GPT-J 6B, GPT-NeoX 20B. More example configs can be found in [Cerebras Model Zoo](https://github.com/Cerebras/modelzoo/tree/master/modelzoo/models/nlp/gptj/configs). * Added new GPT-3 variants up to 20B parameters both in TensorFlow and PyTorch. * Improved performance (throughput) for GPT-style models by up to 1.5x compared to the previous release. #### Computer vision models * Added support for UNet 2D in Weight Streaming execution to enable large input sizes of up to 5k x 5k resolutions. Both Training and Eval workflows are supported. Single CS-2 system support only. Single-channel single-class segmentation only in this release. ### Other features * Added support for bfloat16 data type for large language models in PyTorch and enabled precision knobs for performance optimization. * Added support for training language models with sparse weights in PyTorch; training with static sparsity masks is now enabled, and scripts to convert a dense PyTorch checkpoint into a sparse version are available. * Improved error messages for easy-to-understand, user-actionable errors. * Expanded support for PyTorch learning rate schedules and loss functions. ### Known issues #### Running eval with UNet in PyTorch, Weight Streaming execution * UNet model eval with metrics mIOU, DSC on images of size 4096 x 4096 pixels causes failures and is a known issue. All default configurations and image sizes published in the Model Zoo have been tested and expected to work without issues. The issue may manifest itself with other non-tested image sizes. The expected error is as follows: ```Bash theme={null} status = StatusCode.INTERNAL details = "KM to RT IR Translation Failed" debug_error_string = "UNKNOWN:Error received from peer ipv4:10.254.104.16:443 {grpc_message:"KM to RT IR Translation Failed", grpc_status:13, created_time:"2022-12-15T00:27:47.134671257-08:00"}" ``` Please contact Cerebras support if you run into failures. ## Release 1.6.1 ### New features and enhancements #### Weight Streaming models in PyTorch * Early access support for GPT model variants, up to 1.5B parameters in PyTorch on single CS-2 systems. #### Security-related Updates and Error fixes * Restricts the weight streaming jobs to be run with respective uid/gid security context only and disallows root user * Creation of volume mounts is now limited to worker nodes only to avoid security issues from broader access. * Adds new feature of “KeepAlive” to coordinator node in appliance which helps to keep track of the client activity and prevents jobs from hanging indefinitely * Pipeline workflow in Appliance now uses the scheduler to choose the CS system automatically and doesn’t require user to specify the `cs_ip` explicitly ## Release 1.6.0 ### New features and enhancements #### Weight streaming models * Up to 2x performance improvement for GPT-style models with weight streaming training on CS-2 systems. * Early access support for additional GPT model variants, up to 20B parameters on single CS-2 systems. #### Cerebras Wafer-Scale Cluster * This is the first production release of software support for weight streaming on the Cerebras Wafer-Scale Cluster. This includes a simple workflow that allows users to easily submit and scale large training jobs to a Cerebras cluster. Refer to our TF and PyTorch getting started guides on how to run your pipeline and weight streaming models on the cluster. #### Multi-node CS-2 support * Expands Cerebras Wafer-Scale Cluster to support 8x CS-2s on GPT-style models and achieves near linear scaling performance. #### PyTorch support * Introduces Cerebras PyTorch Layer API that implements a subset of PyTorch APIs with Cerebras custom implementations that take advantage of our high-performance kernels and provides drop-in replacement to the native PyTorch version. * Includes a demo of GPT2 model that uses the Layer API and implements the model. * Added support for label-smoothed cross entropy for pipelined models in PyTorch. #### Cerebras Model Zoo * Launched a public version of Cerebras sample model implementations through [Cerebras Model Zoo github repository](https://github.com/Cerebras/modelzoo). ## Release 1.5.0 ### New features and enhancements #### Weight streaming * Significant performance boost in the evaluation of accuracy for large-scale GPT models. Evaluation performance is now on par with training performance. * Added support for vocab sizes up to 231 for GPT-style models when run with weight streaming execution. #### Multi-node CS-2 support * Expands Cerebras Wafer-Scale Cluster to support 4x CS-2s on GPT-style models. * Cerebras Wafer-Scale Clusters are composed of CS-2 systems, MemoryX and SwarmX nodes, input pre-processing servers and associated internal network switches. End-user workflow is supported via appliance model, where the user submits a job to the cluster as if it were a single device. > [!NOTE] > > Note > > To learn more and get a demo of our cluster capabilities and appliance workflow, contact Cerebras support by sending email to [support@cerebras.net](mailto:support%40cerebras.net). > [!NOTE] > > Note > > CSoft 1.5 deprecates some of our experimental models that were brittle and not suitable to run with many variants of model implementation. The deprecated models are: RNN, GNN, CTR, Audio and RevBERT which were previously supported in demo mode. ## Release 1.4.0 ### New features and enhancements #### Weight Streaming * Single CS-2 System now supports training of multi-billion parameter NLP models including GPT-3XL 1.3 billion, GPT-J 6 billion, GPT-3 13 billion and more via the weight streaming mode of execution. * Training on GPT-J (6B parameters) is now supported for longer sequences up to 30K tokens on single CS-2 system. * Switching between these extreme scale models can be achieved by just a few changes in config file. #### PyTorch models * We have made performance Improvements for small- to medium-sized PyTorch models through support for Multi-Replica (MR) + Variable Tensor Shape (VTS), including: - Multi-replica improves fabric utilization and throughput performance. - VTS improves performance for dataset with variable length sequence. * Models now support MR + VTS: BERT, Transformer (AIAYN) and T5. * We added an adafactor optimizer support to T5 model in PyTorch to achieve robust convergence. #### TensorFlow models * We have added support for a multi-replica mode and variable sequence length to T5 model in pipeline execution to further boost performance on CS-2 System. #### Multi-node CS-2 support * This release introduces 2X CS-2 cluster in demo mode that leverages a weight streaming support cluster (composed of CS2 systems, MemoryX and SwarmX systems, worker servers and associated internal network switches) to efficiently run extreme scale NLP models. * The end-to-end user workflow can be thought of and handled as a single network-attached service appliance. In this appliance model, the user submits a job to the weight streaming cluster as if it were a single device. > [!NOTE] > > Note > > To learn more and get a demo of our cluster capabilities and appliance workflow, contact Cerebras support by sending email to [support@cerebras.net](mailto:support%40cerebras.net). ### Known issues #### Running eval on Cerebras system When running in `eval` mode on CS-1 system, if `--nodes` and `--tasks_per_node` value pairs are **not** set to one of the following, then the session may hang. This issue exists for both TensorFlow and PyTorch. 1. `--nodes==1 --tasks_per_node=2`, or 2. \`--nodes==2 --tasks\_per\_node=1\`\`\`\`Bash \--nodes=1 --tasks\_per\_node=2\`\`\`\`Bash csrun\_wse python run.py --mode=eval \--nodes=1 --tasks\_per\_node=2 \--params configs/your-params-file.yaml \--model\_dir your-model-dir \--cs\_ip=10.255.253.0\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` ``` 1. **Workaound**: Make sure that you use one of the above settings for `--nodes` and `--tasks_per_node`. For example: 1) The `eval` performance is not affected by these Slurm resource settings. See the example command below: ``` ## Release 1.3.0 ### New features and enhancements #### PyTorch models * Supports Variable Tensor Shapes (VTS) for Transformer, T5 and BERT models, which boosts performance significantly * Added support for BERT Finetuning tasks: SQUAD (Q\&A), Classifier (SST) and Summarization (SUM) * Supports fixed positional embeddings. * Upgrades to the latest version of PyTorch 1.11. #### Weight streaming mode * GPT-J 6B-parameter model in Tensorflow is supported for pretraining on single CS-2 system * The abstractive summarization fine-tuning task supported for GPT-J (6B parameters). * Eval metrics supported for GPT-2, GPT-3 variants, GPT-J. Metrics include perplexity, accuracy and BPB, BPC, BPW. > [!NOTE] > > Note > > If you are interested in these models, contact Cerebras support by sending email to `support@cerebras.net`. #### Multi-replica mode * Multi-replica mode is now supported across Transformer and BERT Tensorflow models. * Multi-replica mode also adds Variable Tensor Shape support to further boost performance for these models. ### Known issues #### GPT-J (6B parameters) model * There is a non-determinism on the GPU side we are currently debugging, so in order to match the GPU reference, CS-2 run should start from the same initial checkpoint. * There is an unexplained shuffle happening when the input function runs out of data and needs to repeat the dataset. So, in order to get the exact match, the reference should run for less number of steps than the dataset, or the dataset needs to be extended, so that repeat doesn’t happen. * When running the GPT-J 6B model, each weight streaming server should be configured to have 512 GB of total memory. It is recommended to have at least 128 GB of physical memory and any remainder as swap space. #### Running eval on Cerebras system When running in `eval` mode on CS-1 system, if `--nodes` and `--tasks_per_node` value pairs are **not** set to one of the following, then the session may hang. This issue exists for both TensorFlow and PyTorch. 1. `--nodes==1 --tasks_per_node=2`, or 2. \`--nodes==2 --tasks\_per\_node=1\`\`\`\`Bash \--nodes=1 --tasks\_per\_node=2\`\`\`\`Bash csrun\_wse python run.py --mode=eval \--nodes=1 --tasks\_per\_node=2 \--params configs/your-params-file.yaml \--model\_dir your-model-dir \--cs\_ip=10.255.253.0\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` ``` 1. **Workaound**: Make sure that you use one of the above settings for `--nodes` and `--tasks_per_node`. For example: 1) The `eval` performance is not affected by these Slurm resource settings. See the example command below: ``` *** ## Release 1.2.0 ### New features and enhancements #### PyTorch models * Train and Eval mode is now supported for PyTorch BERT Base with sequences upto 4k tokens and BERT Large with sequences upto 2k tokens. Includes support for common eval metrics (eval loss, MLM accuracy, NSP accuracy, perplexity). * Train and Eval mode is now supported for RoBERTa configuration in PyTorch BERT. * Adds support for BERT-NER finetuning * Train and Eval mode is now supported for the PyTorch Transformer-Attention is All You Need model. * Train and Eval mode is now supported for PyTorch T5 model with configurations up to \~500M parameters, e.g., T5-Small 60M and T5-Base 220M * Train and Eval mode is now supported for PyTorch GPT-2 model with configurations with up to \~770M parameters, e.g., GPT-2 Small 117M, GPT-2 Medium 345M, GPT-2 Large 774M #### Weight streaming execution mode * A new execution mode, called **weight streaming** mode, to run extremely large models, is introduced as an early release. See [Weight Streaming Execution](../concepts/weight-streaming-execution) for a detailed explanation of the weight streaming concept. * In weight streaming mode, support is added for eval on GPU. * In weight streaming mode, support is added to store checkpoints and resume training from checkpoints. * Support is added in weight streaming mode to track training runs with TensorBoard. #### Weight streaming models The following models support weight streaming mode. These models are in early beta. * GPT-3 XL (1.3 billion total parameters) running on a single CS-2 system. > [!NOTE] > > Note > > If you are interested in these models, contact Cerebras support by sending email to `support@cerebras.net`. #### Input analyzer for Slurm resources * The `cs_input_analyzer` is a new Bash script that recommends Slurm resource settings you need to run on Cerebras system. These recommendations are generated by this script for a given `input_fn` and model. To use this tool, run it manually. See The cs\_input\_analyzer Script ### Known issues #### Running eval on Cerebras system When running in `eval` mode on CS-1 system, if `--nodes` and `--tasks_per_node` value pairs are **not** set to one of the following, then the session may hang. This issue exists for both TensorFlow and PyTorch. 1. `--nodes==1 --tasks_per_node=2`, or 2. `--nodes==2 --tasks_per_node=1` 3. **Workaound**: Make sure that you use one of the above settings for `--nodes` and `--tasks_per_node`. For example: ```Bash theme={null} --nodes=1 --tasks_per_node=2 ``` 1. The `eval` performance is not affected by these Slurm resource settings. See the example command below: ```Bash theme={null} csrun_wse python run.py --mode=eval \ --nodes=1 --tasks_per_node=2 \ --params configs/your-params-file.yaml \ --model_dir your-model-dir \ --cs_ip=10.255.253.0 ``` Release 1.1.0 ### New features and enhancements #### PyTorch * The PyTorch support is enhanced. Key changes include but not limited to: * Support for `eval` mode is added for BERT and FC-MNIST PyTorch models. These models now support both `train` and `eval` modes. * Enhanced the flexibility in specifying the `cerebras.framework.torch.initialize()`. * Use of `cbfloat16` data format (see CB16 Half-Precision is now supported. * Made mixed precision interface more intuitive, via `GradScaler` (see [Dynamic loss scaling](../model-zoo/tutorials/dynamic-loss-scaling)). * Fixed several bugs in the areas of numerics, convergence and performance. ##### PyTorch models The following PyTorch models are supported. * A PyTorch version of FC-MNIST. * The PyTorch versions of BERT Base and BERT Large. * RoBERTa (Next Sentence Prediction (NSP) only) configurations are supported. See `roberta_base.yaml` and `roberta_large.yaml`. * Longer Maximum Sequence Length (MSL) configurations are supported, at least up to MSL 4096. * The PyTorch Transformer-Attention is All You Need model is added as a Beta feature.This model can be compiled using `run.py` with the `--compile_only` flag, as well as run on CPU or GPU using `run_cpu_gpu.py`.To train this model on the Cerebras System at your own risk, comment out the following lines from `run.py`:\`\`\`Bash if not runconfig\_params\["compile\_only"]: raise ValueError( "Running the Transformer model on the Cerebras System is in beta." "Convergence is not guaranteed. Remove this exception to proceed." )\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` ``` ``` > [!NOTE] > > Note > > If you are interested in these models, contact Cerebras support by sending email to `support@cerebras.net`. ##### Supported PyTorch ops * A preliminary list of supported PyTorch ops is released. #### Multi-replica data parallel training A new feature called **multi-replica data parallel training** is released. Currently this feature is available only for TensorFlow models. When you use this feature, the Cerebras compiler uses several copies (replicas) of the same model to run data parallel training. ### Known issues #### T5 and Transformer (Attention is All You Need) * The TensorFlow versions of the T5 and Transformer models are not guaranteed to converge. These models can still be compiled to the Cerebras system. However, to train these models on the Cerebras System at your own risk, comment out the following lines from `run.py` of the model:\`\`\`Bash if not runconfig\_params\["compile\_only"]: raise ValueError( "Running the Transformer model on the Cerebras System is in beta." "Convergence is not guaranteed. Remove this exception to proceed." )\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` ``` ``` * When you train the TensorFlow Transformer model on Cerebras system, you will see a modest increase in loss volatility, compared to the runs on GPUs. This is due to numerical differences. The pre-training eval accuracy is expected to be within a few percent of the equivalent model trained on a GPU. > [!NOTE] > > Note > > If you are interested in these models, contact Cerebras support by sending email to `support@cerebras.net`. #### Running eval on Cerebras system When running in `eval` mode on CS-1 system, if `--nodes` and `--tasks_per_node` value pairs are **not** set to one of the following, then the session may hang. This issue exists for both TensorFlow and PyTorch. 1. `--nodes==1 --tasks_per_node=2`, or 2. \`--nodes==2 --tasks\_per\_node=1\`\`\`\`Bash \--nodes=1 --tasks\_per\_node=2\`\`\`\`Bash csrun\_wse python run.py --mode=eval \--nodes=1 --tasks\_per\_node=2 \--params configs/your-params-file.yaml \--model\_dir your-model-dir \--cs\_ip=10.255.253.0\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` ``` 1. **Workaound**: Make sure that you use one of the above settings for `--nodes` and `--tasks_per_node`. For example: 1) The `eval` performance is not affected by these Slurm resource settings. See the example command below: ``` #### Multi-replica data parallel training * Eval on Cerebras system is not yet supported for multi-replica data parallel trained models. You can run eval on CPU or GPU for these models. #### PyTorch * For PyTorch, when you are targeting GPU, the following warning will be displayed. This can be safely ignored. This issue does not exist when you target Cerebras system for your acceleration. ```Bash theme={null} UserWarning: Detected call of ``lr_scheduler.step()`` before ``optimizer.step()``. In PyTorch 1.1.0 and later, you should call them in the opposite order: ``optimizer.step()`` before ``lr_scheduler.step()``. Failure to do this will result in PyTorch skipping the first value of the learning rate schedule. ``` * For PyTorch models only, to run the training on the Cerebras system, the `cs_ip` flag must include both the IP address and the port number of the CS system. Only the IP address, for example: `--cs_ip 192.168.1.1`, will not be sufficient. You must also include the port number, for example: `--cs_ip 192.168.1.1:9000`. *** ## Release 1.0.0 ### New features and enhancements #### PyTorch (BETA) Support is added, in beta phase only, for the PyTorch framework. The models and quickstart provided are strictly intended as advanced information only. * A PyTorch version of FC-MNIST is added as a part of PyTorch (BETA) support.This version only supports compiling on a CPU node with the `train` mode. To train this model on the Cerebras System at your own risk, edit the `run.py` file and comment out the entire `raise ValueError()` function, as shown below:\`\`\`Bash elif runconfig\_params\["mode"] == TRAIN:# raise ValueError(# "Training PyTorch models on the Cerebras System is in beta "# "and is only validated with the default config provided in the "# "Model Zoo. Remove this exception and use the provided config to"# "proceed."#) runner.train(train\_loader)\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` ``` ``` * The PyTorch versions of BERT Base and BERT Large are added as a part of PyTorch (BETA) support.These versions only support compiling on a CPU node with the `train` mode. To train these models on the Cerebras System at your own risk, edit the `run.py` file and comment out the entire `raise ValueError()` function, as shown below:\`\`\`Bash elif runconfig\_params\["mode"] == TRAIN: \#raise ValueError( \#"Training PyTorch models on the Cerebras System is in beta " \#"and is only validated with the default configs provided in the " \#"Model Zoo. Remove this exception and use one of the provided " \#"configs to proceed." \#) runner.train(train\_loader)\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` ``` ``` #### RevBERT A new TensorFlow model, the RevBERT is introduced. The RevBERT is a Cerebras-specific BERT model that improves the BERT performance on Cerebras accelerator. Using the RevBERT model you can run up to 20x larger batch sizes and 2.7x larger models on the Cerebras System. This version of RevBERT is only supported with TensorFlow and only supports the `train` mode. > [!NOTE] > > Note > > If you are interested in these models, contact Cerebras support by sending email to `support@cerebras.net`. #### Transformer (Attention Is All You Need) Support is added in the `train` mode for Variable Sequence Length (VSL) on the CS system. #### T5 model * Support is enhanced from loss-only eval to full eval metrics. * Support is added in the `train` mode for Variable Sequence Length (VSL) on the CS system. #### GPT-2 Support is added in the `train` mode for Variable Sequence Length (VSL) on the CS system. *** ## Release 0.9.0\[#] ### New features and enhancements\[#] Two new Slurm wrapper scripts are introduced to make it easy to run on CS system and on the CPU. These scripts will replace `srun_train` and `salloc_node`. See below: * The `csrun_wse` script can be used to execute training, evaluation and prediction on the CS system. * The `csrun_cpu` script can be used to launch a given user command on a CPU, within the Cerebras Singularity container. Support is added for the [Transformer (Attention Is All You Need)](https://arxiv.org/abs/1706.03762), with the following capabilities: * Example dataset and preprocessing scripts for English-to-German translation included. * On CS system: Training, and Eval (loss only). * On GPU: Train, Eval (`eval` and `eval_all`). Support is added for the [following T5](https://arxiv.org/abs/1910.10683) family of models: * Small model: * dmodel = 512 * dff = 2,048. * 8-headed attention. * 6 layers each in the encoder and decoder. * About 60 million parameters. * Model: * Base, BERT Base-sized encoder and decoder. * About \~ 220 million parameters. * Model: Large, BERT Large-sized encoder and decoder. * dmodel = 1,024. * dff = 4,096. * dkv = 64. * 16-headed attention. * 24 layers each in the encoder and decoder. * Around 770 million parameters. * Sample dataset: [Colossal Clean Crawled Corpus (C4) dataset](https://github.com/allenai/allennlp/discussions/5056). * On CS system: Pre-training, Eval (loss only). * On GPU: Train, Eval (`eval` and `eval_all`). The variable sequence length (VSL) performance of BERT-style encoder-decoder models is enhanced. Previously, a sequence of less than pre-defined maximum sequence length is padded up to the maximum sequence length. The compute and memory are also spent on processing these tokens used for padding, resulting in a significant loss of performance. With this enhancement, by taking advantage of the sparsity the tokens used for padding are not processed, thereby enhancing the performance of the variable length sequences. The performance-optimized variable sequence length is now available for the following models on the CS system: * BERT Pre-training (training only). * RNN Language Model (LM) (training only). * RNN Sentiment (training only). Performance is enhanced for long sequences (MSL up to 8K for smaller models) for BERT- and GPT-style models. This is accomplished by making use of sparse attention to reduce memory requirements. ### Known issues * When you use AdamW Optimizer and if both the following conditions are true: * The parameter `weight_decay` is set to a non-zero value, and * The parameter `loss_scaling_factor` is not set to “dynamic”. then the execution will stop with the following error message: > [!NOTE] > > Error > > “When using the AdamW optimizer with weight decay, set the `loss_scaling_factor` to dynamic.” * For the models T5 and Transformer (Attention Is All You Need), the performance in samples-per-sec is optimal when the source `max_seq_len` and the target `max_seq_len` are equal. * When running evaluation with a BERT model, if the `max_predictions_per_seq` parameter is set to an odd value and if the following conditions are true: * The tensor is multi-dimensional (>1D). * The inner dimension is an odd value. * The datatype is \< 4 bytes, i.e., FP16 or INT16 or UINT16. then this leads to a compile failure in 0.9.0 and execution failure in 0.8.0. **Workaround**: Set the `max_predictions_per_seq` parameter to an even value. > [!NOTE] > > Note > > If you are interested in these models, contact Cerebras support by sending email to `support@cerebras.net`. *** ## Release 0.8.0 ### New features and enhancements * Inference is now supported for the following models: * Graph Convolutional Network * Graph Attention Network > [!NOTE] > > Note > > If you are interested in these models, contact Cerebras support by sending email to `support@cerebras.net`. * A new feature, multi-model inference, is introduced. Using this you can run multiple neural network models on the CS system, send inference requests to these models and receive prediction responses. * Early stopping is now supported using a custom hook called `CerebrasEarlyStoppingHook`. Using this hook, you can terminate early a neural network training based on some logic. *** ## Release 0.7.1 ### New features and enhancements * Evaluation and prediction are now supported on the CS system for BERT networks. While executing the `run.py`, you can run evaluation or prediction with your network as follows: * **Evaluation**: Use `--mode eval` to use the evaluation feature. * **Prediction**: Use `--mode predict` to use the prediction feature. *** ## Release 0.7.0- ### New features and enhancements * Performance is improved for BERT Large models with MSL 512. This is accomplished by making a tradeoff that mitigates the need for large buffer memory. * Support is added for combined Dice loss and Softmax Cross-entropy (CE) loss. * Support for TensorFlow summaries is added. * A new datatype called CB16 is introduced. The CB16 is Cerebras’ 16-bit format, also referred to as `cbfloat16`. The CB16 is a floating-point format with 6-bit exponent and 9-bit explicit mantissa. This allows for double the dynamic range of FP16. See [Control numerical precision level](../model-zoo/components/trainer-components/numeric-precision). * A new feature that projects the performance of your network is added to the Cerebras Graph Compiler (CGC). Now when your compile is successful, the generated report includes projections on how your network might perform on the CS system.: * A new feature called incremental compile is added to the Cerebras Graph Compiler (CGC). After you compile your model the first time, the incremental compile feature of CGC will automatically speed up the subsequent compile runs of your model by reusing, wherever possible, the optimizations already performed. * The input function analyzer is enhanced. Now called `analyze_input_fn_compile`, this tool provides a detailed log identifying any missing functions and provides recommendations on parameter values to enhance the training performance on the CS system. * Introduced a new method called Cerebras AUTOTUNE (`CS_AUTOTUNE`), which is similar to the TensorFlow `tf.data.AUTOTUNE`. When you are targeting the CS system, using `CS_AUTOTUNE` instead of `tf.data.AUTOTUNE` will result in a better specification of parameters such as: * `num_parallel_calls` * `cycle_length` * `num_parallel_reads` * A new function, `KerasModelToCerebrasEstimator`, is provided to convert a Keras model so the model can be run using the `CerebrasEstimator`. * While setting the runtime configuration options, in v0.6.3 and earlier versions you were required to add the following code for the Slurm cluster resolver. ```Bash theme={null} from cerebras.tf.cs_slurm_cluster_resolver import CSSlurmClusterResolver slurm_cluster_resolver = CSSlurmClusterResolver() cluster_spec = slurm_cluster_resolver.cluster_spec() task_type, task_id = slurm_cluster_resolver.get_task_info() os.environ['TF_CONFIG'] = json.dumps({ 'cluster': cluster_spec.as_dict(), 'task': {'type': task_type, 'index': task_id} }) ``` Now this is done automatically. This means that your Slurm-orchestrated TensorFlow code that contains the above statements should be edited as follows: ```Bash theme={null} # Do not remove the following import statement. from cerebras.tf.cs_slurm_cluster_resolver import CSSlurmClusterResolver # Remove the following lines starting CGC v0.7.0. slurm_cluster_resolver = CSSlurmClusterResolver() cluster_spec = slurm_cluster_resolver.cluster_spec() task_type, task_id = slurm_cluster_resolver.get_task_info() os.environ['TF_CONFIG'] = json.dumps({ 'cluster': cluster_spec.as_dict(), 'task': {'type': task_type, 'index': task_id} }) ``` #### Breaking changes * The `use_cs` parameter in the cerebras estimator interface is removed and will result in compiler error if used in this API. The target hardware will now be automatically determined from a combination of the runtime configuration parameter `cs_ip` and the `use_cs` parameter setting in the method definitions for `train`. * The format of the YAML config files for all the models is changed as follows: * All the training-related parameters have been moved to the `runconfig` section. * The `max_steps` parameter is added as a default parameter to control the duration of training. ### Known issues[#](#id63 "Permalink to this headline") * For BERT, a change in the `max_gradient_norm` hyperparameter value will not result in reduced incremental compile times. * In v0.6.3, in some cases, when you enable dynamic loss scaling and an arbitrary operation is performed on the computed loss, then the Cerebras compiler may give error and fail to compile.**Workaround**: In v0.7.0 you can workaround this error by disabling the dynamic loss scaling by setting `loss_scaling_factor` to a constant value either equal to or greater than 1.0. *** ## Release 0.6.3 ### New features and enhancements * The overall performance is improved for BERT for max sequence length 128 (MSL128) variants. This improvement varies based on the fabric and model configuration. Enable the following custom Cerebras configuration flag only for BERT MSL128 variants to see this performance improvement: ```Bash theme={null} config.matching.kernel.no\_dcache\_spill_splits = True ``` > [!TIP] > > Tip > > The Cerebras implementation sets this flag by default for BERT runs with MSL128. * The kernel matching phase of the Cerebras Graph Compiler (CGC) is enhanced to significantly reduce the kernel matching time and improve flexibility. With this enhancement, the kernel matching phase is completed within 60 seconds in a majority of cases. As a result, the overall compile time will be reduced in these cases. ### Resolved issues * Resolved a kernel matching issue with 1DConv models with embeddings, when a Conv1D layer is stacked on top of an embedding layer. # Previous Releases Source: https://training-docs.cerebras.ai/rel-2.5.0/support/previous-releases Access documentation for previous releases using the links below. * [Release 2.3.1](https://training-api.cerebras.ai/en/rel-2.3.1/index.html) * [Release 2.3.0](https://training-api.cerebras.ai/en/rel-2.3.0/index.html) * [Release 2.2.1](https://training-api.cerebras.ai/en/rel-2.2.1/) * [Release 2.2.0](https://training-api.cerebras.ai/en/2.1.1/) * [Release 2.1.1](https://training-api.cerebras.ai/en/2.1.1/) * [Release 2.1.0](https://training-api.cerebras.ai/en/2.1.0/) * [Release 2.0.3](https://training-api.cerebras.ai/en/2.0.2/) * [Release 2.0.2](https://training-api.cerebras.ai/en/1.9.1/) * [Release 1.9.1](https://training-api.cerebras.ai/en/1.9.1/) * [Release 1.8.0](https://training-api.cerebras.ai/en/1.7.1/) * [Release 1.7.1](https://training-api.cerebras.ai/en/1.7.1/) * [Release 1.7.0](https://training-api.cerebras.ai/en/1.7.0/) * [Release 1.6.1](https://training-api.cerebras.ai/en/1.6.1/) - This version is for our weight-streaming clusters. Please use this version for pipeline cluster documentation. * [Release 1.6.0](https://training-api.cerebras.ai/en/1.5.0/) * [Release 1.5.0](https://training-api.cerebras.ai/en/1.5.0/)