import json
import os
from dask.distributed import Client
from devitohorizon.cloud import ec2_cluster
from devitohorizon.data import Dataset
from devitohorizon.physics import DevitoPhysics
from devitohorizon.scheduler import DaskScheduler
os.environ['DEVITO_LOGGING'] = 'ERROR'AWS Dask Workflow
Shows the API for using datasets and models on S3, starting an EC2 Dask cluster, and running distributed gradient computations through physics.objective() with a DaskScheduler.
Prerequisites: an AWS credentials file (aws_creds.json, written by scripts/make_aws_creds.sh), a SEG-Y shot dataset and an initial model already uploaded to the bucket. Cells that provision cloud resources are marked NBVAL_SKIP.
Credentials
make_aws_creds.sh writes no access keys by default. The file says "provider": "s3", which tells horizon the paths are on S3 and the credentials are already there – from your own AWS configuration on this machine, and from the IAM instance profile on each worker.
That distinction matters: an empty credentials mapping means the local filesystem, so a run configured that way would write to whichever machine drove it. "provider": "s3" is what says “on S3, credentials ambient”.
# NBVAL_SKIP
with open('aws_creds.json') as f:
creds = json.load(f)
bucket = creds['container_name']
print('Using bucket:', bucket)Using bucket: bp2007
# NBVAL_SKIP
# The BP 2007 TTI shots and Vp model, both at the root of the bucket.
# `Dataset.from_segy` takes the prefix: it scans it for *.segy, which is the
# eight BPTTI gathers -- Vp_Model.sgy is a .sgy and so is not swept up as data.
param = {
'nbl': 40,
'space_order': 8,
'parameters': ('m',),
'gradient': {'mute_type': 'datum'},
'data_path': bucket,
'model_file': 'Vp_Model_scalco.sgy',
}
print(param['data_path'], '/', param['model_file'])bp2007 / Vp_Model_scalco.sgy
The cluster
ec2_cluster checks this client’s dask stack against the pins the worker image is built with before an instance is billed, opens the scheduler ports to this machine’s current public IP, and sizes each node for one Devito shot (one dask thread, no nanny memory limit, OpenMP on).
The nodes pull the image from ECR with a token they fetch themselves at boot, which is why instance_profile in the credentials matters: it is what gives them ECR pull rights, and what lets them read the bucket without carrying any keys.
# NBVAL_SKIP
# Provision an EC2 cluster (requires credentials and quota)
#
# `dask:aws` is the tag the helper pulls by default, and it is published only
# by a merge to main: a pull request publishes `aws-pr<N>` instead, so that it
# can be tried on a real cluster without replacing what every cluster starts
# from. Until this branch merges, name the pull request's own image.
image = f"{creds['docker_registry']}/devitohorizon/dask:aws-pr57"
cluster = ec2_cluster(creds, instance_type='m5.large', n_workers=4,
docker_image=image)
client = Client(cluster)
print('Dashboard:', client.dashboard_link)Opening scheduler ports (8786, 8787) to 99.161.90.33/32 on security group sg-06439d822b5bcddf9 (rule 'dask-client')
Replacing 2 previous 'dask-client' ingress rule(s)
Creating scheduler instance
Created instance i-0311881f7388e64fd as dask-b8fb6a36-scheduler
Waiting for scheduler to run at ec2-18-191-167-120.us-east-2.compute.amazonaws.com:8786
Scheduler is running
/opt/homebrew/Cellar/python@3.10/3.10.21/Frameworks/Python.framework/Versions/3.10/lib/python3.10/contextlib.py:142: UserWarning: Creating your cluster is taking a surprisingly long time. This is likely due to pending resources. Hang tight!
next(self.gen)
Creating worker instance
Creating worker instance
Creating worker instance
Creating worker instance
Created instance i-0cb9c207075749267 as dask-b8fb6a36-worker-d1fde5f0
Created instance i-05ec87882c34fe4e3 as dask-b8fb6a36-worker-52b33309
Created instance i-031836b5bcc0890fe as dask-b8fb6a36-worker-d227fef0
Created instance i-0d159d57cb9ca43cc as dask-b8fb6a36-worker-c1e36807
Dashboard: http://ec2-18-191-167-120.us-east-2.compute.amazonaws.com:8787/status
/Users/mathiaslouboutin/Devitos/venv-horizon-py310/lib/python3.10/site-packages/distributed/client.py:1595: VersionMismatchWarning: Mismatched versions found
+---------+-----------------+-----------------+---------+
| Package | Client | Scheduler | Workers |
+---------+-----------------+-----------------+---------+
| python | 3.10.21.final.0 | 3.10.12.final.0 | None |
+---------+-----------------+-----------------+---------+
warnings.warn(version_module.VersionMismatchWarning(msg[0]["warning"]))
client = Client(cluster)
print('Dashboard:', client.dashboard_link)Dashboard: http://ec2-18-191-167-120.us-east-2.compute.amazonaws.com:8787/status
# NBVAL_SKIP
# Load observed shot data from S3. Shots travel to workers by reference --
# each one carries the filesystem and its own byte ranges, and reads its
# traces back on the worker.
dataset = Dataset.from_segy(f"s3://{param['data_path']}", creds=creds)
print(f'Loaded {len(dataset.shot_ids)} shots')Loaded scan of 8 shots from s3://bp2007/.segy_scan.all.segy.pkl
Dataset: 8 shots
Samples: ns=1151, dt=8.00 ms, tn=9.20 s
Source X: [27800.0, 65600.0]
Source Y: [0.0, 0.0]
Source Z: [0.0, 0.0]
Traces/shot: [800, 800]
Loaded 8 shots
# NBVAL_SKIP
# The model needs its own credentials and container, not just a path that
# happens to name one: they are what lets a worker open the model, and what
# tells the run it has storage every node can reach. Without them the staged
# model and the compiled operators go to a local directory the workers
# cannot see.
physics = DevitoPhysics(
nbl=param['nbl'],
space_order=param['space_order'],
parameters=param['parameters'],
model={'model': {'vp': param['model_file']},
'container_name': bucket,
'creds': creds},
gradient=param['gradient'],
creds=creds,
container_name=bucket,
)
print('Shots available:', len(dataset))Shots available: 8
# NBVAL_SKIP
# Submit distributed gradient computation via Dask
# Index with a sequence, not a comprehension: `dataset[[...]]` is a
# Dataset subset and still carries the acquisition surface, which a
# plain list of shots does not and a datum mute needs.
# shots = dataset[[0, 2, 4, 6]]
scheduler = DaskScheduler(client)
image = physics.image(dataset, scheduler=scheduler)Prebuilding operators on a worker...
Operators prebuilt and cached successfully
Finalizing reduced gradient with 2 step(s). Surface mute type: datum, Global smoothing: False
print('Gradient shape:', image.shape)Gradient shape: (12596, 1801)
import pysegy
pysegy.plot_simage(image.T, (6.25, 6.25), name='gradient')
client.close()
cluster.close()Terminated dask-b8fb6a36-worker-d1fde5f0 (i-0cb9c207075749267)
Terminated dask-b8fb6a36-worker-52b33309 (i-05ec87882c34fe4e3)
Terminated dask-b8fb6a36-worker-d227fef0 (i-031836b5bcc0890fe)
Terminated dask-b8fb6a36-worker-c1e36807 (i-0d159d57cb9ca43cc)
Terminated dask-b8fb6a36-scheduler (i-0311881f7388e64fd)