Upload 5 files
Browse files- CONTRIBUTING.md +25 -0
- LICENSE +202 -0
- README.md +133 -0
- graphcast_demo.ipynb +853 -0
- setup.py +61 -0
CONTRIBUTING.md
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# How to Contribute
|
2 |
+
|
3 |
+
## Contributor License Agreement
|
4 |
+
|
5 |
+
Contributions to this project must be accompanied by a Contributor License
|
6 |
+
Agreement. You (or your employer) retain the copyright to your contribution,
|
7 |
+
this simply gives us permission to use and redistribute your contributions as
|
8 |
+
part of the project. Head over to <https://cla.developers.google.com/> to see
|
9 |
+
your current agreements on file or to sign a new one.
|
10 |
+
|
11 |
+
You generally only need to submit a CLA once, so if you've already submitted one
|
12 |
+
(even if it was for a different project), you probably don't need to do it
|
13 |
+
again.
|
14 |
+
|
15 |
+
## Code reviews
|
16 |
+
|
17 |
+
All submissions, including submissions by project members, require review. We
|
18 |
+
use GitHub pull requests for this purpose. Consult
|
19 |
+
[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
|
20 |
+
information on using pull requests.
|
21 |
+
|
22 |
+
## Community Guidelines
|
23 |
+
|
24 |
+
This project follows [Google's Open Source Community
|
25 |
+
Guidelines](https://opensource.google/conduct/).
|
LICENSE
ADDED
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
Apache License
|
3 |
+
Version 2.0, January 2004
|
4 |
+
http://www.apache.org/licenses/
|
5 |
+
|
6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
7 |
+
|
8 |
+
1. Definitions.
|
9 |
+
|
10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
12 |
+
|
13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
14 |
+
the copyright owner that is granting the License.
|
15 |
+
|
16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
17 |
+
other entities that control, are controlled by, or are under common
|
18 |
+
control with that entity. For the purposes of this definition,
|
19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
20 |
+
direction or management of such entity, whether by contract or
|
21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
23 |
+
|
24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
25 |
+
exercising permissions granted by this License.
|
26 |
+
|
27 |
+
"Source" form shall mean the preferred form for making modifications,
|
28 |
+
including but not limited to software source code, documentation
|
29 |
+
source, and configuration files.
|
30 |
+
|
31 |
+
"Object" form shall mean any form resulting from mechanical
|
32 |
+
transformation or translation of a Source form, including but
|
33 |
+
not limited to compiled object code, generated documentation,
|
34 |
+
and conversions to other media types.
|
35 |
+
|
36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
37 |
+
Object form, made available under the License, as indicated by a
|
38 |
+
copyright notice that is included in or attached to the work
|
39 |
+
(an example is provided in the Appendix below).
|
40 |
+
|
41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
42 |
+
form, that is based on (or derived from) the Work and for which the
|
43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
45 |
+
of this License, Derivative Works shall not include works that remain
|
46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
47 |
+
the Work and Derivative Works thereof.
|
48 |
+
|
49 |
+
"Contribution" shall mean any work of authorship, including
|
50 |
+
the original version of the Work and any modifications or additions
|
51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
55 |
+
means any form of electronic, verbal, or written communication sent
|
56 |
+
to the Licensor or its representatives, including but not limited to
|
57 |
+
communication on electronic mailing lists, source code control systems,
|
58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
60 |
+
excluding communication that is conspicuously marked or otherwise
|
61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
62 |
+
|
63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
65 |
+
subsequently incorporated within the Work.
|
66 |
+
|
67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
72 |
+
Work and such Derivative Works in Source or Object form.
|
73 |
+
|
74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
77 |
+
(except as stated in this section) patent license to make, have made,
|
78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
79 |
+
where such license applies only to those patent claims licensable
|
80 |
+
by such Contributor that are necessarily infringed by their
|
81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
83 |
+
institute patent litigation against any entity (including a
|
84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
85 |
+
or a Contribution incorporated within the Work constitutes direct
|
86 |
+
or contributory patent infringement, then any patent licenses
|
87 |
+
granted to You under this License for that Work shall terminate
|
88 |
+
as of the date such litigation is filed.
|
89 |
+
|
90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
91 |
+
Work or Derivative Works thereof in any medium, with or without
|
92 |
+
modifications, and in Source or Object form, provided that You
|
93 |
+
meet the following conditions:
|
94 |
+
|
95 |
+
(a) You must give any other recipients of the Work or
|
96 |
+
Derivative Works a copy of this License; and
|
97 |
+
|
98 |
+
(b) You must cause any modified files to carry prominent notices
|
99 |
+
stating that You changed the files; and
|
100 |
+
|
101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
102 |
+
that You distribute, all copyright, patent, trademark, and
|
103 |
+
attribution notices from the Source form of the Work,
|
104 |
+
excluding those notices that do not pertain to any part of
|
105 |
+
the Derivative Works; and
|
106 |
+
|
107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
108 |
+
distribution, then any Derivative Works that You distribute must
|
109 |
+
include a readable copy of the attribution notices contained
|
110 |
+
within such NOTICE file, excluding those notices that do not
|
111 |
+
pertain to any part of the Derivative Works, in at least one
|
112 |
+
of the following places: within a NOTICE text file distributed
|
113 |
+
as part of the Derivative Works; within the Source form or
|
114 |
+
documentation, if provided along with the Derivative Works; or,
|
115 |
+
within a display generated by the Derivative Works, if and
|
116 |
+
wherever such third-party notices normally appear. The contents
|
117 |
+
of the NOTICE file are for informational purposes only and
|
118 |
+
do not modify the License. You may add Your own attribution
|
119 |
+
notices within Derivative Works that You distribute, alongside
|
120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
121 |
+
that such additional attribution notices cannot be construed
|
122 |
+
as modifying the License.
|
123 |
+
|
124 |
+
You may add Your own copyright statement to Your modifications and
|
125 |
+
may provide additional or different license terms and conditions
|
126 |
+
for use, reproduction, or distribution of Your modifications, or
|
127 |
+
for any such Derivative Works as a whole, provided Your use,
|
128 |
+
reproduction, and distribution of the Work otherwise complies with
|
129 |
+
the conditions stated in this License.
|
130 |
+
|
131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
133 |
+
by You to the Licensor shall be under the terms and conditions of
|
134 |
+
this License, without any additional terms or conditions.
|
135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
136 |
+
the terms of any separate license agreement you may have executed
|
137 |
+
with Licensor regarding such Contributions.
|
138 |
+
|
139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
141 |
+
except as required for reasonable and customary use in describing the
|
142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
143 |
+
|
144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
145 |
+
agreed to in writing, Licensor provides the Work (and each
|
146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
148 |
+
implied, including, without limitation, any warranties or conditions
|
149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
151 |
+
appropriateness of using or redistributing the Work and assume any
|
152 |
+
risks associated with Your exercise of permissions under this License.
|
153 |
+
|
154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
155 |
+
whether in tort (including negligence), contract, or otherwise,
|
156 |
+
unless required by applicable law (such as deliberate and grossly
|
157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
158 |
+
liable to You for damages, including any direct, indirect, special,
|
159 |
+
incidental, or consequential damages of any character arising as a
|
160 |
+
result of this License or out of the use or inability to use the
|
161 |
+
Work (including but not limited to damages for loss of goodwill,
|
162 |
+
work stoppage, computer failure or malfunction, or any and all
|
163 |
+
other commercial damages or losses), even if such Contributor
|
164 |
+
has been advised of the possibility of such damages.
|
165 |
+
|
166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
169 |
+
or other liability obligations and/or rights consistent with this
|
170 |
+
License. However, in accepting such obligations, You may act only
|
171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
172 |
+
of any other Contributor, and only if You agree to indemnify,
|
173 |
+
defend, and hold each Contributor harmless for any liability
|
174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
175 |
+
of your accepting any such warranty or additional liability.
|
176 |
+
|
177 |
+
END OF TERMS AND CONDITIONS
|
178 |
+
|
179 |
+
APPENDIX: How to apply the Apache License to your work.
|
180 |
+
|
181 |
+
To apply the Apache License to your work, attach the following
|
182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
183 |
+
replaced with your own identifying information. (Don't include
|
184 |
+
the brackets!) The text should be enclosed in the appropriate
|
185 |
+
comment syntax for the file format. We also recommend that a
|
186 |
+
file or class name and description of purpose be included on the
|
187 |
+
same "printed page" as the copyright notice for easier
|
188 |
+
identification within third-party archives.
|
189 |
+
|
190 |
+
Copyright [yyyy] [name of copyright owner]
|
191 |
+
|
192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
193 |
+
you may not use this file except in compliance with the License.
|
194 |
+
You may obtain a copy of the License at
|
195 |
+
|
196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
197 |
+
|
198 |
+
Unless required by applicable law or agreed to in writing, software
|
199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
201 |
+
See the License for the specific language governing permissions and
|
202 |
+
limitations under the License.
|
README.md
CHANGED
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# GraphCast: Learning skillful medium-range global weather forecasting
|
2 |
+
|
3 |
+
This package contains example code to run and train [GraphCast](https://www.science.org/doi/10.1126/science.adi2336).
|
4 |
+
It also provides three pretrained models:
|
5 |
+
|
6 |
+
1. `GraphCast`, the high-resolution model used in the GraphCast paper (0.25 degree
|
7 |
+
resolution, 37 pressure levels), trained on ERA5 data from 1979 to 2017,
|
8 |
+
|
9 |
+
2. `GraphCast_small`, a smaller, low-resolution version of GraphCast (1 degree
|
10 |
+
resolution, 13 pressure levels, and a smaller mesh), trained on ERA5 data from
|
11 |
+
1979 to 2015, useful to run a model with lower memory and compute constraints,
|
12 |
+
|
13 |
+
3. `GraphCast_operational`, a high-resolution model (0.25 degree resolution, 13
|
14 |
+
pressure levels) pre-trained on ERA5 data from 1979 to 2017 and fine-tuned on
|
15 |
+
HRES data from 2016 to 2021. This model can be initialized from HRES data (does
|
16 |
+
not require precipitation inputs).
|
17 |
+
|
18 |
+
The model weights, normalization statistics, and example inputs are available on [Google Cloud Bucket](https://console.cloud.google.com/storage/browser/dm_graphcast).
|
19 |
+
|
20 |
+
Full model training requires downloading the
|
21 |
+
[ERA5](https://www.ecmwf.int/en/forecasts/datasets/reanalysis-datasets/era5)
|
22 |
+
dataset, available from [ECMWF](https://www.ecmwf.int/). This can best be
|
23 |
+
accessed as Zarr from [Weatherbench2's ERA5 data](https://weatherbench2.readthedocs.io/en/latest/data-guide.html#era5) (see the 6h downsampled versions).
|
24 |
+
|
25 |
+
## Overview of files
|
26 |
+
|
27 |
+
The best starting point is to open `graphcast_demo.ipynb` in [Colaboratory](https://colab.research.google.com/github/deepmind/graphcast/blob/master/graphcast_demo.ipynb), which gives an
|
28 |
+
example of loading data, generating random weights or load a pre-trained
|
29 |
+
snapshot, generating predictions, computing the loss and computing gradients.
|
30 |
+
The one-step implementation of GraphCast architecture, is provided in
|
31 |
+
`graphcast.py`.
|
32 |
+
|
33 |
+
### Brief description of library files:
|
34 |
+
|
35 |
+
* `autoregressive.py`: Wrapper used to run (and train) the one-step GraphCast
|
36 |
+
to produce a sequence of predictions by auto-regressively feeding the
|
37 |
+
outputs back as inputs at each step, in JAX a differentiable way.
|
38 |
+
* `casting.py`: Wrapper used around GraphCast to make it work using
|
39 |
+
BFloat16 precision.
|
40 |
+
* `checkpoint.py`: Utils to serialize and deserialize trees.
|
41 |
+
* `data_utils.py`: Utils for data preprocessing.
|
42 |
+
* `deep_typed_graph_net.py`: General purpose deep graph neural network (GNN)
|
43 |
+
that operates on `TypedGraph`'s where both inputs and outputs are flat
|
44 |
+
vectors of features for each of the nodes and edges. `graphcast.py` uses
|
45 |
+
three of these for the Grid2Mesh GNN, the Multi-mesh GNN and the Mesh2Grid
|
46 |
+
GNN, respectively.
|
47 |
+
* `graphcast.py`: The main GraphCast model architecture for one-step of
|
48 |
+
predictions.
|
49 |
+
* `grid_mesh_connectivity.py`: Tools for converting between regular grids on a
|
50 |
+
sphere and triangular meshes.
|
51 |
+
* `icosahedral_mesh.py`: Definition of an icosahedral multi-mesh.
|
52 |
+
* `losses.py`: Loss computations, including latitude-weighting.
|
53 |
+
* `model_utils.py`: Utilities to produce flat node and edge vector features
|
54 |
+
from input grid data, and to manipulate the node output vectors back
|
55 |
+
into a multilevel grid data.
|
56 |
+
* `normalization.py`: Wrapper for the one-step GraphCast used to normalize
|
57 |
+
inputs according to historical values, and targets according to historical
|
58 |
+
time differences.
|
59 |
+
* `predictor_base.py`: Defines the interface of the predictor, which GraphCast
|
60 |
+
and all of the wrappers implement.
|
61 |
+
* `rollout.py`: Similar to `autoregressive.py` but used only at inference time
|
62 |
+
using a python loop to produce longer, but non-differentiable trajectories.
|
63 |
+
* `solar_radiation.py`: Computes Top-Of-the-Atmosphere (TOA) incident solar
|
64 |
+
radiation compatible with ERA5. This is used as a forcing variable and thus
|
65 |
+
needs to be computed for target lead times in an operational setting.
|
66 |
+
* `typed_graph.py`: Definition of `TypedGraph`'s.
|
67 |
+
* `typed_graph_net.py`: Implementation of simple graph neural network
|
68 |
+
building blocks defined over `TypedGraph`'s that can be combined to build
|
69 |
+
deeper models.
|
70 |
+
* `xarray_jax.py`: A wrapper to let JAX work with `xarray`s.
|
71 |
+
* `xarray_tree.py`: An implementation of tree.map_structure that works with
|
72 |
+
`xarray`s.
|
73 |
+
|
74 |
+
|
75 |
+
### Dependencies.
|
76 |
+
|
77 |
+
[Chex](https://github.com/deepmind/chex),
|
78 |
+
[Dask](https://github.com/dask/dask),
|
79 |
+
[Haiku](https://github.com/deepmind/dm-haiku),
|
80 |
+
[JAX](https://github.com/google/jax),
|
81 |
+
[JAXline](https://github.com/deepmind/jaxline),
|
82 |
+
[Jraph](https://github.com/deepmind/jraph),
|
83 |
+
[Numpy](https://numpy.org/),
|
84 |
+
[Pandas](https://pandas.pydata.org/),
|
85 |
+
[Python](https://www.python.org/),
|
86 |
+
[SciPy](https://scipy.org/),
|
87 |
+
[Tree](https://github.com/deepmind/tree),
|
88 |
+
[Trimesh](https://github.com/mikedh/trimesh) and
|
89 |
+
[XArray](https://github.com/pydata/xarray).
|
90 |
+
|
91 |
+
|
92 |
+
### License and attribution
|
93 |
+
|
94 |
+
The Colab notebook and the associated code are licensed under the Apache
|
95 |
+
License, Version 2.0. You may obtain a copy of the License at:
|
96 |
+
https://www.apache.org/licenses/LICENSE-2.0.
|
97 |
+
|
98 |
+
The model weights are made available for use under the terms of the Creative
|
99 |
+
Commons Attribution-NonCommercial-ShareAlike 4.0 International
|
100 |
+
(CC BY-NC-SA 4.0). You may obtain a copy of the License at:
|
101 |
+
https://creativecommons.org/licenses/by-nc-sa/4.0/.
|
102 |
+
|
103 |
+
The weights were trained on ECMWF's ERA5 and HRES data. The colab includes a few
|
104 |
+
examples of ERA5 and HRES data that can be used as inputs to the models.
|
105 |
+
ECMWF data product are subject to the following terms:
|
106 |
+
|
107 |
+
1. Copyright statement: Copyright "© 2023 European Centre for Medium-Range Weather Forecasts (ECMWF)".
|
108 |
+
2. Source www.ecmwf.int
|
109 |
+
3. Licence Statement: ECMWF data is published under a Creative Commons Attribution 4.0 International (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/
|
110 |
+
4. Disclaimer: ECMWF does not accept any liability whatsoever for any error or omission in the data, their availability, or for any loss or damage arising from their use.
|
111 |
+
|
112 |
+
### Disclaimer
|
113 |
+
|
114 |
+
This is not an officially supported Google product.
|
115 |
+
|
116 |
+
Copyright 2023 DeepMind Technologies Limited.
|
117 |
+
|
118 |
+
### Citation
|
119 |
+
|
120 |
+
If you use this work, consider citing our paper ([blog post](https://deepmind.google/discover/blog/graphcast-ai-model-for-faster-and-more-accurate-global-weather-forecasting/), [Science](https://www.science.org/doi/10.1126/science.adi2336), [arXiv](https://arxiv.org/abs/2212.12794)):
|
121 |
+
|
122 |
+
```latex
|
123 |
+
@article{lam2023learning,
|
124 |
+
title={Learning skillful medium-range global weather forecasting},
|
125 |
+
author={Lam, Remi and Sanchez-Gonzalez, Alvaro and Willson, Matthew and Wirnsberger, Peter and Fortunato, Meire and Alet, Ferran and Ravuri, Suman and Ewalds, Timo and Eaton-Rosen, Zach and Hu, Weihua and others},
|
126 |
+
journal={Science},
|
127 |
+
volume={382},
|
128 |
+
number={6677},
|
129 |
+
pages={1416--1421},
|
130 |
+
year={2023},
|
131 |
+
publisher={American Association for the Advancement of Science}
|
132 |
+
}
|
133 |
+
```
|
graphcast_demo.ipynb
ADDED
@@ -0,0 +1,853 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"metadata": {
|
6 |
+
"id": "-jAYlxeKxvAJ"
|
7 |
+
},
|
8 |
+
"source": [
|
9 |
+
"# GraphCast\n",
|
10 |
+
"\n",
|
11 |
+
"This colab lets you run several versions of GraphCast.\n",
|
12 |
+
"\n",
|
13 |
+
"The model weights, normalization statistics, and example inputs are available on [Google Cloud Bucket](https://console.cloud.google.com/storage/browser/dm_graphcast).\n",
|
14 |
+
"\n",
|
15 |
+
"A Colab runtime with TPU/GPU acceleration will substantially speed up generating predictions and computing the loss/gradients. If you're using a CPU-only runtime, you can switch using the menu \"Runtime \u003e Change runtime type\"."
|
16 |
+
]
|
17 |
+
},
|
18 |
+
{
|
19 |
+
"cell_type": "markdown",
|
20 |
+
"metadata": {
|
21 |
+
"id": "IIWlNRupdI2i"
|
22 |
+
},
|
23 |
+
"source": [
|
24 |
+
"\u003e \u003cp\u003e\u003csmall\u003e\u003csmall\u003eCopyright 2023 DeepMind Technologies Limited.\u003c/small\u003e\u003c/p\u003e\n",
|
25 |
+
"\u003e \u003cp\u003e\u003csmall\u003e\u003csmall\u003eLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at \u003ca href=\"http://www.apache.org/licenses/LICENSE-2.0\"\u003ehttp://www.apache.org/licenses/LICENSE-2.0\u003c/a\u003e.\u003c/small\u003e\u003c/small\u003e\u003c/p\u003e\n",
|
26 |
+
"\u003e \u003cp\u003e\u003csmall\u003e\u003csmall\u003eUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\u003c/small\u003e\u003c/small\u003e\u003c/p\u003e"
|
27 |
+
]
|
28 |
+
},
|
29 |
+
{
|
30 |
+
"cell_type": "markdown",
|
31 |
+
"metadata": {
|
32 |
+
"id": "yMbbXFl4msJw"
|
33 |
+
},
|
34 |
+
"source": [
|
35 |
+
"# Installation and Initialization\n"
|
36 |
+
]
|
37 |
+
},
|
38 |
+
{
|
39 |
+
"cell_type": "code",
|
40 |
+
"execution_count": null,
|
41 |
+
"metadata": {
|
42 |
+
"cellView": "form",
|
43 |
+
"id": "-W4K9skv9vh-"
|
44 |
+
},
|
45 |
+
"outputs": [],
|
46 |
+
"source": [
|
47 |
+
"# @title Pip install graphcast and dependencies\n",
|
48 |
+
"\n",
|
49 |
+
"%pip install --upgrade https://github.com/deepmind/graphcast/archive/master.zip"
|
50 |
+
]
|
51 |
+
},
|
52 |
+
{
|
53 |
+
"cell_type": "code",
|
54 |
+
"execution_count": null,
|
55 |
+
"metadata": {
|
56 |
+
"cellView": "form",
|
57 |
+
"id": "MA5087Vb29z2"
|
58 |
+
},
|
59 |
+
"outputs": [],
|
60 |
+
"source": [
|
61 |
+
"# @title Workaround for cartopy crashes\n",
|
62 |
+
"\n",
|
63 |
+
"# Workaround for cartopy crashes due to the shapely installed by default in\n",
|
64 |
+
"# google colab kernel (https://github.com/anitagraser/movingpandas/issues/81):\n",
|
65 |
+
"!pip uninstall -y shapely\n",
|
66 |
+
"!pip install shapely --no-binary shapely"
|
67 |
+
]
|
68 |
+
},
|
69 |
+
{
|
70 |
+
"cell_type": "code",
|
71 |
+
"execution_count": null,
|
72 |
+
"metadata": {
|
73 |
+
"cellView": "form",
|
74 |
+
"id": "Z_j8ej4Pyg1L"
|
75 |
+
},
|
76 |
+
"outputs": [],
|
77 |
+
"source": [
|
78 |
+
"# @title Imports\n",
|
79 |
+
"\n",
|
80 |
+
"import dataclasses\n",
|
81 |
+
"import datetime\n",
|
82 |
+
"import functools\n",
|
83 |
+
"import math\n",
|
84 |
+
"import re\n",
|
85 |
+
"from typing import Optional\n",
|
86 |
+
"\n",
|
87 |
+
"import cartopy.crs as ccrs\n",
|
88 |
+
"from google.cloud import storage\n",
|
89 |
+
"from graphcast import autoregressive\n",
|
90 |
+
"from graphcast import casting\n",
|
91 |
+
"from graphcast import checkpoint\n",
|
92 |
+
"from graphcast import data_utils\n",
|
93 |
+
"from graphcast import graphcast\n",
|
94 |
+
"from graphcast import normalization\n",
|
95 |
+
"from graphcast import rollout\n",
|
96 |
+
"from graphcast import xarray_jax\n",
|
97 |
+
"from graphcast import xarray_tree\n",
|
98 |
+
"from IPython.display import HTML\n",
|
99 |
+
"import ipywidgets as widgets\n",
|
100 |
+
"import haiku as hk\n",
|
101 |
+
"import jax\n",
|
102 |
+
"import matplotlib\n",
|
103 |
+
"import matplotlib.pyplot as plt\n",
|
104 |
+
"from matplotlib import animation\n",
|
105 |
+
"import numpy as np\n",
|
106 |
+
"import xarray\n",
|
107 |
+
"\n",
|
108 |
+
"\n",
|
109 |
+
"def parse_file_parts(file_name):\n",
|
110 |
+
" return dict(part.split(\"-\", 1) for part in file_name.split(\"_\"))\n"
|
111 |
+
]
|
112 |
+
},
|
113 |
+
{
|
114 |
+
"cell_type": "code",
|
115 |
+
"execution_count": null,
|
116 |
+
"metadata": {
|
117 |
+
"cellView": "form",
|
118 |
+
"id": "4wagX1TL_f15"
|
119 |
+
},
|
120 |
+
"outputs": [],
|
121 |
+
"source": [
|
122 |
+
"# @title Authenticate with Google Cloud Storage\n",
|
123 |
+
"\n",
|
124 |
+
"gcs_client = storage.Client.create_anonymous_client()\n",
|
125 |
+
"gcs_bucket = gcs_client.get_bucket(\"dm_graphcast\")"
|
126 |
+
]
|
127 |
+
},
|
128 |
+
{
|
129 |
+
"cell_type": "code",
|
130 |
+
"execution_count": null,
|
131 |
+
"metadata": {
|
132 |
+
"cellView": "form",
|
133 |
+
"id": "5JUymx84dI2m"
|
134 |
+
},
|
135 |
+
"outputs": [],
|
136 |
+
"source": [
|
137 |
+
"# @title Plotting functions\n",
|
138 |
+
"\n",
|
139 |
+
"def select(\n",
|
140 |
+
" data: xarray.Dataset,\n",
|
141 |
+
" variable: str,\n",
|
142 |
+
" level: Optional[int] = None,\n",
|
143 |
+
" max_steps: Optional[int] = None\n",
|
144 |
+
" ) -\u003e xarray.Dataset:\n",
|
145 |
+
" data = data[variable]\n",
|
146 |
+
" if \"batch\" in data.dims:\n",
|
147 |
+
" data = data.isel(batch=0)\n",
|
148 |
+
" if max_steps is not None and \"time\" in data.sizes and max_steps \u003c data.sizes[\"time\"]:\n",
|
149 |
+
" data = data.isel(time=range(0, max_steps))\n",
|
150 |
+
" if level is not None and \"level\" in data.coords:\n",
|
151 |
+
" data = data.sel(level=level)\n",
|
152 |
+
" return data\n",
|
153 |
+
"\n",
|
154 |
+
"def scale(\n",
|
155 |
+
" data: xarray.Dataset,\n",
|
156 |
+
" center: Optional[float] = None,\n",
|
157 |
+
" robust: bool = False,\n",
|
158 |
+
" ) -\u003e tuple[xarray.Dataset, matplotlib.colors.Normalize, str]:\n",
|
159 |
+
" vmin = np.nanpercentile(data, (2 if robust else 0))\n",
|
160 |
+
" vmax = np.nanpercentile(data, (98 if robust else 100))\n",
|
161 |
+
" if center is not None:\n",
|
162 |
+
" diff = max(vmax - center, center - vmin)\n",
|
163 |
+
" vmin = center - diff\n",
|
164 |
+
" vmax = center + diff\n",
|
165 |
+
" return (data, matplotlib.colors.Normalize(vmin, vmax),\n",
|
166 |
+
" (\"RdBu_r\" if center is not None else \"viridis\"))\n",
|
167 |
+
"\n",
|
168 |
+
"def plot_data(\n",
|
169 |
+
" data: dict[str, xarray.Dataset],\n",
|
170 |
+
" fig_title: str,\n",
|
171 |
+
" plot_size: float = 5,\n",
|
172 |
+
" robust: bool = False,\n",
|
173 |
+
" cols: int = 4\n",
|
174 |
+
" ) -\u003e tuple[xarray.Dataset, matplotlib.colors.Normalize, str]:\n",
|
175 |
+
"\n",
|
176 |
+
" first_data = next(iter(data.values()))[0]\n",
|
177 |
+
" max_steps = first_data.sizes.get(\"time\", 1)\n",
|
178 |
+
" assert all(max_steps == d.sizes.get(\"time\", 1) for d, _, _ in data.values())\n",
|
179 |
+
"\n",
|
180 |
+
" cols = min(cols, len(data))\n",
|
181 |
+
" rows = math.ceil(len(data) / cols)\n",
|
182 |
+
" figure = plt.figure(figsize=(plot_size * 2 * cols,\n",
|
183 |
+
" plot_size * rows))\n",
|
184 |
+
" figure.suptitle(fig_title, fontsize=16)\n",
|
185 |
+
" figure.subplots_adjust(wspace=0, hspace=0)\n",
|
186 |
+
" figure.tight_layout()\n",
|
187 |
+
"\n",
|
188 |
+
" images = []\n",
|
189 |
+
" for i, (title, (plot_data, norm, cmap)) in enumerate(data.items()):\n",
|
190 |
+
" ax = figure.add_subplot(rows, cols, i+1)\n",
|
191 |
+
" ax.set_xticks([])\n",
|
192 |
+
" ax.set_yticks([])\n",
|
193 |
+
" ax.set_title(title)\n",
|
194 |
+
" im = ax.imshow(\n",
|
195 |
+
" plot_data.isel(time=0, missing_dims=\"ignore\"), norm=norm,\n",
|
196 |
+
" origin=\"lower\", cmap=cmap)\n",
|
197 |
+
" plt.colorbar(\n",
|
198 |
+
" mappable=im,\n",
|
199 |
+
" ax=ax,\n",
|
200 |
+
" orientation=\"vertical\",\n",
|
201 |
+
" pad=0.02,\n",
|
202 |
+
" aspect=16,\n",
|
203 |
+
" shrink=0.75,\n",
|
204 |
+
" cmap=cmap,\n",
|
205 |
+
" extend=(\"both\" if robust else \"neither\"))\n",
|
206 |
+
" images.append(im)\n",
|
207 |
+
"\n",
|
208 |
+
" def update(frame):\n",
|
209 |
+
" if \"time\" in first_data.dims:\n",
|
210 |
+
" td = datetime.timedelta(microseconds=first_data[\"time\"][frame].item() / 1000)\n",
|
211 |
+
" figure.suptitle(f\"{fig_title}, {td}\", fontsize=16)\n",
|
212 |
+
" else:\n",
|
213 |
+
" figure.suptitle(fig_title, fontsize=16)\n",
|
214 |
+
" for im, (plot_data, norm, cmap) in zip(images, data.values()):\n",
|
215 |
+
" im.set_data(plot_data.isel(time=frame, missing_dims=\"ignore\"))\n",
|
216 |
+
"\n",
|
217 |
+
" ani = animation.FuncAnimation(\n",
|
218 |
+
" fig=figure, func=update, frames=max_steps, interval=250)\n",
|
219 |
+
" plt.close(figure.number)\n",
|
220 |
+
" return HTML(ani.to_jshtml())"
|
221 |
+
]
|
222 |
+
},
|
223 |
+
{
|
224 |
+
"cell_type": "markdown",
|
225 |
+
"metadata": {
|
226 |
+
"id": "WEtSV8HEkHtf"
|
227 |
+
},
|
228 |
+
"source": [
|
229 |
+
"# Load the Data and initialize the model"
|
230 |
+
]
|
231 |
+
},
|
232 |
+
{
|
233 |
+
"cell_type": "markdown",
|
234 |
+
"metadata": {
|
235 |
+
"id": "G50ORsY_dI2n"
|
236 |
+
},
|
237 |
+
"source": [
|
238 |
+
"## Load the model params\n",
|
239 |
+
"\n",
|
240 |
+
"Choose one of the two ways of getting model params:\n",
|
241 |
+
"- **random**: You'll get random predictions, but you can change the model architecture, which may run faster or fit on your device.\n",
|
242 |
+
"- **checkpoint**: You'll get sensible predictions, but are limited to the model architecture that it was trained with, which may not fit on your device. In particular generating gradients uses a lot of memory, so you'll need at least 25GB of ram (TPUv4 or A100).\n",
|
243 |
+
"\n",
|
244 |
+
"Checkpoints vary across a few axes:\n",
|
245 |
+
"- The mesh size specifies the internal graph representation of the earth. Smaller meshes will run faster but will have worse outputs. The mesh size does not affect the number of parameters of the model.\n",
|
246 |
+
"- The resolution and number of pressure levels must match the data. Lower resolution and fewer levels will run a bit faster. Data resolution only affects the encoder/decoder.\n",
|
247 |
+
"- All our models predict precipitation. However, ERA5 includes precipitation, while HRES does not. Our models marked as \"ERA5\" take precipitation as input and expect ERA5 data as input, while model marked \"ERA5-HRES\" do not take precipitation as input and are specifically trained to take HRES-fc0 as input (see the data section below).\n",
|
248 |
+
"\n",
|
249 |
+
"We provide three pre-trained models.\n",
|
250 |
+
"1. `GraphCast`, the high-resolution model used in the GraphCast paper (0.25 degree resolution, 37 pressure levels), trained on ERA5 data from 1979 to 2017,\n",
|
251 |
+
"\n",
|
252 |
+
"2. `GraphCast_small`, a smaller, low-resolution version of GraphCast (1 degree resolution, 13 pressure levels, and a smaller mesh), trained on ERA5 data from 1979 to 2015, useful to run a model with lower memory and compute constraints,\n",
|
253 |
+
"\n",
|
254 |
+
"3. `GraphCast_operational`, a high-resolution model (0.25 degree resolution, 13 pressure levels) pre-trained on ERA5 data from 1979 to 2017 and fine-tuned on HRES data from 2016 to 2021. This model can be initialized from HRES data (does not require precipitation inputs).\n"
|
255 |
+
]
|
256 |
+
},
|
257 |
+
{
|
258 |
+
"cell_type": "code",
|
259 |
+
"execution_count": null,
|
260 |
+
"metadata": {
|
261 |
+
"cellView": "form",
|
262 |
+
"id": "KGaJ6V9MdI2n"
|
263 |
+
},
|
264 |
+
"outputs": [],
|
265 |
+
"source": [
|
266 |
+
"# @title Choose the model\n",
|
267 |
+
"\n",
|
268 |
+
"params_file_options = [\n",
|
269 |
+
" name for blob in gcs_bucket.list_blobs(prefix=\"params/\")\n",
|
270 |
+
" if (name := blob.name.removeprefix(\"params/\"))] # Drop empty string.\n",
|
271 |
+
"\n",
|
272 |
+
"random_mesh_size = widgets.IntSlider(\n",
|
273 |
+
" value=4, min=4, max=6, description=\"Mesh size:\")\n",
|
274 |
+
"random_gnn_msg_steps = widgets.IntSlider(\n",
|
275 |
+
" value=4, min=1, max=32, description=\"GNN message steps:\")\n",
|
276 |
+
"random_latent_size = widgets.Dropdown(\n",
|
277 |
+
" options=[int(2**i) for i in range(4, 10)], value=32,description=\"Latent size:\")\n",
|
278 |
+
"random_levels = widgets.Dropdown(\n",
|
279 |
+
" options=[13, 37], value=13, description=\"Pressure levels:\")\n",
|
280 |
+
"\n",
|
281 |
+
"\n",
|
282 |
+
"params_file = widgets.Dropdown(\n",
|
283 |
+
" options=params_file_options,\n",
|
284 |
+
" description=\"Params file:\",\n",
|
285 |
+
" layout={\"width\": \"max-content\"})\n",
|
286 |
+
"\n",
|
287 |
+
"source_tab = widgets.Tab([\n",
|
288 |
+
" widgets.VBox([\n",
|
289 |
+
" random_mesh_size,\n",
|
290 |
+
" random_gnn_msg_steps,\n",
|
291 |
+
" random_latent_size,\n",
|
292 |
+
" random_levels,\n",
|
293 |
+
" ]),\n",
|
294 |
+
" params_file,\n",
|
295 |
+
"])\n",
|
296 |
+
"source_tab.set_title(0, \"Random\")\n",
|
297 |
+
"source_tab.set_title(1, \"Checkpoint\")\n",
|
298 |
+
"widgets.VBox([\n",
|
299 |
+
" source_tab,\n",
|
300 |
+
" widgets.Label(value=\"Run the next cell to load the model. Rerunning this cell clears your selection.\")\n",
|
301 |
+
"])\n"
|
302 |
+
]
|
303 |
+
},
|
304 |
+
{
|
305 |
+
"cell_type": "code",
|
306 |
+
"execution_count": null,
|
307 |
+
"metadata": {
|
308 |
+
"cellView": "form",
|
309 |
+
"id": "lYQgrPgPdI2n"
|
310 |
+
},
|
311 |
+
"outputs": [],
|
312 |
+
"source": [
|
313 |
+
"# @title Load the model\n",
|
314 |
+
"\n",
|
315 |
+
"source = source_tab.get_title(source_tab.selected_index)\n",
|
316 |
+
"\n",
|
317 |
+
"if source == \"Random\":\n",
|
318 |
+
" params = None # Filled in below\n",
|
319 |
+
" state = {}\n",
|
320 |
+
" model_config = graphcast.ModelConfig(\n",
|
321 |
+
" resolution=0,\n",
|
322 |
+
" mesh_size=random_mesh_size.value,\n",
|
323 |
+
" latent_size=random_latent_size.value,\n",
|
324 |
+
" gnn_msg_steps=random_gnn_msg_steps.value,\n",
|
325 |
+
" hidden_layers=1,\n",
|
326 |
+
" radius_query_fraction_edge_length=0.6)\n",
|
327 |
+
" task_config = graphcast.TaskConfig(\n",
|
328 |
+
" input_variables=graphcast.TASK.input_variables,\n",
|
329 |
+
" target_variables=graphcast.TASK.target_variables,\n",
|
330 |
+
" forcing_variables=graphcast.TASK.forcing_variables,\n",
|
331 |
+
" pressure_levels=graphcast.PRESSURE_LEVELS[random_levels.value],\n",
|
332 |
+
" input_duration=graphcast.TASK.input_duration,\n",
|
333 |
+
" )\n",
|
334 |
+
"else:\n",
|
335 |
+
" assert source == \"Checkpoint\"\n",
|
336 |
+
" with gcs_bucket.blob(f\"params/{params_file.value}\").open(\"rb\") as f:\n",
|
337 |
+
" ckpt = checkpoint.load(f, graphcast.CheckPoint)\n",
|
338 |
+
" params = ckpt.params\n",
|
339 |
+
" state = {}\n",
|
340 |
+
"\n",
|
341 |
+
" model_config = ckpt.model_config\n",
|
342 |
+
" task_config = ckpt.task_config\n",
|
343 |
+
" print(\"Model description:\\n\", ckpt.description, \"\\n\")\n",
|
344 |
+
" print(\"Model license:\\n\", ckpt.license, \"\\n\")\n",
|
345 |
+
"\n",
|
346 |
+
"model_config"
|
347 |
+
]
|
348 |
+
},
|
349 |
+
{
|
350 |
+
"cell_type": "markdown",
|
351 |
+
"metadata": {
|
352 |
+
"id": "rQWk0RRuCjDN"
|
353 |
+
},
|
354 |
+
"source": [
|
355 |
+
"## Load the example data\n",
|
356 |
+
"\n",
|
357 |
+
"Several example datasets are available, varying across a few axes:\n",
|
358 |
+
"- **Source**: fake, era5, hres\n",
|
359 |
+
"- **Resolution**: 0.25deg, 1deg, 6deg\n",
|
360 |
+
"- **Levels**: 13, 37\n",
|
361 |
+
"- **Steps**: How many timesteps are included\n",
|
362 |
+
"\n",
|
363 |
+
"Not all combinations are available.\n",
|
364 |
+
"- Higher resolution is only available for fewer steps due to the memory requirements of loading them.\n",
|
365 |
+
"- HRES is only available in 0.25 deg, with 13 pressure levels.\n",
|
366 |
+
"\n",
|
367 |
+
"The data resolution must match the model that is loaded.\n",
|
368 |
+
"\n",
|
369 |
+
"Some transformations were done from the base datasets:\n",
|
370 |
+
"- We accumulated precipitation over 6 hours instead of the default 1 hour.\n",
|
371 |
+
"- For HRES data, each time step corresponds to the HRES forecast at leadtime 0, essentially providing an \"initialisation\" from HRES. See HRES-fc0 in the GraphCast paper for further description. Note that a 6h accumulation of precipitation is not available from HRES, so our model taking HRES inputs does not depend on precipitation. However, because our models predict precipitation, we include the ERA5 precipitation in the example data so it can serve as an illustrative example of ground truth.\n",
|
372 |
+
"- We include ERA5 `toa_incident_solar_radiation` in the data. Our model uses the radiation at -6h, 0h and +6h as a forcing term for each 1-step prediction. If the radiation is missing from the data (e.g. in an operational setting), it will be computed using a custom implementation that produces values similar to those in ERA5."
|
373 |
+
]
|
374 |
+
},
|
375 |
+
{
|
376 |
+
"cell_type": "code",
|
377 |
+
"execution_count": null,
|
378 |
+
"metadata": {
|
379 |
+
"cellView": "form",
|
380 |
+
"id": "-DJzie5me2-H"
|
381 |
+
},
|
382 |
+
"outputs": [],
|
383 |
+
"source": [
|
384 |
+
"# @title Get and filter the list of available example datasets\n",
|
385 |
+
"\n",
|
386 |
+
"dataset_file_options = [\n",
|
387 |
+
" name for blob in gcs_bucket.list_blobs(prefix=\"dataset/\")\n",
|
388 |
+
" if (name := blob.name.removeprefix(\"dataset/\"))] # Drop empty string.\n",
|
389 |
+
"\n",
|
390 |
+
"def data_valid_for_model(\n",
|
391 |
+
" file_name: str, model_config: graphcast.ModelConfig, task_config: graphcast.TaskConfig):\n",
|
392 |
+
" file_parts = parse_file_parts(file_name.removesuffix(\".nc\"))\n",
|
393 |
+
" return (\n",
|
394 |
+
" model_config.resolution in (0, float(file_parts[\"res\"])) and\n",
|
395 |
+
" len(task_config.pressure_levels) == int(file_parts[\"levels\"]) and\n",
|
396 |
+
" (\n",
|
397 |
+
" (\"total_precipitation_6hr\" in task_config.input_variables and\n",
|
398 |
+
" file_parts[\"source\"] in (\"era5\", \"fake\")) or\n",
|
399 |
+
" (\"total_precipitation_6hr\" not in task_config.input_variables and\n",
|
400 |
+
" file_parts[\"source\"] in (\"hres\", \"fake\"))\n",
|
401 |
+
" )\n",
|
402 |
+
" )\n",
|
403 |
+
"\n",
|
404 |
+
"\n",
|
405 |
+
"dataset_file = widgets.Dropdown(\n",
|
406 |
+
" options=[\n",
|
407 |
+
" (\", \".join([f\"{k}: {v}\" for k, v in parse_file_parts(option.removesuffix(\".nc\")).items()]), option)\n",
|
408 |
+
" for option in dataset_file_options\n",
|
409 |
+
" if data_valid_for_model(option, model_config, task_config)\n",
|
410 |
+
" ],\n",
|
411 |
+
" description=\"Dataset file:\",\n",
|
412 |
+
" layout={\"width\": \"max-content\"})\n",
|
413 |
+
"widgets.VBox([\n",
|
414 |
+
" dataset_file,\n",
|
415 |
+
" widgets.Label(value=\"Run the next cell to load the dataset. Rerunning this cell clears your selection and refilters the datasets that match your model.\")\n",
|
416 |
+
"])"
|
417 |
+
]
|
418 |
+
},
|
419 |
+
{
|
420 |
+
"cell_type": "code",
|
421 |
+
"execution_count": null,
|
422 |
+
"metadata": {
|
423 |
+
"cellView": "form",
|
424 |
+
"id": "Yz-ekISoJxeZ"
|
425 |
+
},
|
426 |
+
"outputs": [],
|
427 |
+
"source": [
|
428 |
+
"# @title Load weather data\n",
|
429 |
+
"\n",
|
430 |
+
"if not data_valid_for_model(dataset_file.value, model_config, task_config):\n",
|
431 |
+
" raise ValueError(\n",
|
432 |
+
" \"Invalid dataset file, rerun the cell above and choose a valid dataset file.\")\n",
|
433 |
+
"\n",
|
434 |
+
"with gcs_bucket.blob(f\"dataset/{dataset_file.value}\").open(\"rb\") as f:\n",
|
435 |
+
" example_batch = xarray.load_dataset(f).compute()\n",
|
436 |
+
"\n",
|
437 |
+
"assert example_batch.dims[\"time\"] \u003e= 3 # 2 for input, \u003e=1 for targets\n",
|
438 |
+
"\n",
|
439 |
+
"print(\", \".join([f\"{k}: {v}\" for k, v in parse_file_parts(dataset_file.value.removesuffix(\".nc\")).items()]))\n",
|
440 |
+
"\n",
|
441 |
+
"example_batch"
|
442 |
+
]
|
443 |
+
},
|
444 |
+
{
|
445 |
+
"cell_type": "code",
|
446 |
+
"execution_count": null,
|
447 |
+
"metadata": {
|
448 |
+
"cellView": "form",
|
449 |
+
"id": "lXjFvdE6qStr"
|
450 |
+
},
|
451 |
+
"outputs": [],
|
452 |
+
"source": [
|
453 |
+
"# @title Choose data to plot\n",
|
454 |
+
"\n",
|
455 |
+
"plot_example_variable = widgets.Dropdown(\n",
|
456 |
+
" options=example_batch.data_vars.keys(),\n",
|
457 |
+
" value=\"2m_temperature\",\n",
|
458 |
+
" description=\"Variable\")\n",
|
459 |
+
"plot_example_level = widgets.Dropdown(\n",
|
460 |
+
" options=example_batch.coords[\"level\"].values,\n",
|
461 |
+
" value=500,\n",
|
462 |
+
" description=\"Level\")\n",
|
463 |
+
"plot_example_robust = widgets.Checkbox(value=True, description=\"Robust\")\n",
|
464 |
+
"plot_example_max_steps = widgets.IntSlider(\n",
|
465 |
+
" min=1, max=example_batch.dims[\"time\"], value=example_batch.dims[\"time\"],\n",
|
466 |
+
" description=\"Max steps\")\n",
|
467 |
+
"\n",
|
468 |
+
"widgets.VBox([\n",
|
469 |
+
" plot_example_variable,\n",
|
470 |
+
" plot_example_level,\n",
|
471 |
+
" plot_example_robust,\n",
|
472 |
+
" plot_example_max_steps,\n",
|
473 |
+
" widgets.Label(value=\"Run the next cell to plot the data. Rerunning this cell clears your selection.\")\n",
|
474 |
+
"])"
|
475 |
+
]
|
476 |
+
},
|
477 |
+
{
|
478 |
+
"cell_type": "code",
|
479 |
+
"execution_count": null,
|
480 |
+
"metadata": {
|
481 |
+
"cellView": "form",
|
482 |
+
"id": "kIK-EgMdkHtk"
|
483 |
+
},
|
484 |
+
"outputs": [],
|
485 |
+
"source": [
|
486 |
+
"# @title Plot example data\n",
|
487 |
+
"\n",
|
488 |
+
"plot_size = 7\n",
|
489 |
+
"\n",
|
490 |
+
"data = {\n",
|
491 |
+
" \" \": scale(select(example_batch, plot_example_variable.value, plot_example_level.value, plot_example_max_steps.value),\n",
|
492 |
+
" robust=plot_example_robust.value),\n",
|
493 |
+
"}\n",
|
494 |
+
"fig_title = plot_example_variable.value\n",
|
495 |
+
"if \"level\" in example_batch[plot_example_variable.value].coords:\n",
|
496 |
+
" fig_title += f\" at {plot_example_level.value} hPa\"\n",
|
497 |
+
"\n",
|
498 |
+
"plot_data(data, fig_title, plot_size, plot_example_robust.value)\n"
|
499 |
+
]
|
500 |
+
},
|
501 |
+
{
|
502 |
+
"cell_type": "code",
|
503 |
+
"execution_count": null,
|
504 |
+
"metadata": {
|
505 |
+
"cellView": "form",
|
506 |
+
"id": "tPVy1GHokHtk"
|
507 |
+
},
|
508 |
+
"outputs": [],
|
509 |
+
"source": [
|
510 |
+
"# @title Choose training and eval data to extract\n",
|
511 |
+
"train_steps = widgets.IntSlider(\n",
|
512 |
+
" value=1, min=1, max=example_batch.sizes[\"time\"]-2, description=\"Train steps\")\n",
|
513 |
+
"eval_steps = widgets.IntSlider(\n",
|
514 |
+
" value=example_batch.sizes[\"time\"]-2, min=1, max=example_batch.sizes[\"time\"]-2, description=\"Eval steps\")\n",
|
515 |
+
"\n",
|
516 |
+
"widgets.VBox([\n",
|
517 |
+
" train_steps,\n",
|
518 |
+
" eval_steps,\n",
|
519 |
+
" widgets.Label(value=\"Run the next cell to extract the data. Rerunning this cell clears your selection.\")\n",
|
520 |
+
"])"
|
521 |
+
]
|
522 |
+
},
|
523 |
+
{
|
524 |
+
"cell_type": "code",
|
525 |
+
"execution_count": null,
|
526 |
+
"metadata": {
|
527 |
+
"cellView": "form",
|
528 |
+
"id": "Ogp4vTBvsgSt"
|
529 |
+
},
|
530 |
+
"outputs": [],
|
531 |
+
"source": [
|
532 |
+
"# @title Extract training and eval data\n",
|
533 |
+
"\n",
|
534 |
+
"train_inputs, train_targets, train_forcings = data_utils.extract_inputs_targets_forcings(\n",
|
535 |
+
" example_batch, target_lead_times=slice(\"6h\", f\"{train_steps.value*6}h\"),\n",
|
536 |
+
" **dataclasses.asdict(task_config))\n",
|
537 |
+
"\n",
|
538 |
+
"eval_inputs, eval_targets, eval_forcings = data_utils.extract_inputs_targets_forcings(\n",
|
539 |
+
" example_batch, target_lead_times=slice(\"6h\", f\"{eval_steps.value*6}h\"),\n",
|
540 |
+
" **dataclasses.asdict(task_config))\n",
|
541 |
+
"\n",
|
542 |
+
"print(\"All Examples: \", example_batch.dims.mapping)\n",
|
543 |
+
"print(\"Train Inputs: \", train_inputs.dims.mapping)\n",
|
544 |
+
"print(\"Train Targets: \", train_targets.dims.mapping)\n",
|
545 |
+
"print(\"Train Forcings:\", train_forcings.dims.mapping)\n",
|
546 |
+
"print(\"Eval Inputs: \", eval_inputs.dims.mapping)\n",
|
547 |
+
"print(\"Eval Targets: \", eval_targets.dims.mapping)\n",
|
548 |
+
"print(\"Eval Forcings: \", eval_forcings.dims.mapping)\n"
|
549 |
+
]
|
550 |
+
},
|
551 |
+
{
|
552 |
+
"cell_type": "code",
|
553 |
+
"execution_count": null,
|
554 |
+
"metadata": {
|
555 |
+
"cellView": "form",
|
556 |
+
"id": "Q--ZRhpTdI2o"
|
557 |
+
},
|
558 |
+
"outputs": [],
|
559 |
+
"source": [
|
560 |
+
"# @title Load normalization data\n",
|
561 |
+
"\n",
|
562 |
+
"with gcs_bucket.blob(\"stats/diffs_stddev_by_level.nc\").open(\"rb\") as f:\n",
|
563 |
+
" diffs_stddev_by_level = xarray.load_dataset(f).compute()\n",
|
564 |
+
"with gcs_bucket.blob(\"stats/mean_by_level.nc\").open(\"rb\") as f:\n",
|
565 |
+
" mean_by_level = xarray.load_dataset(f).compute()\n",
|
566 |
+
"with gcs_bucket.blob(\"stats/stddev_by_level.nc\").open(\"rb\") as f:\n",
|
567 |
+
" stddev_by_level = xarray.load_dataset(f).compute()"
|
568 |
+
]
|
569 |
+
},
|
570 |
+
{
|
571 |
+
"cell_type": "code",
|
572 |
+
"execution_count": null,
|
573 |
+
"metadata": {
|
574 |
+
"cellView": "form",
|
575 |
+
"id": "ke2zQyuT_sMA"
|
576 |
+
},
|
577 |
+
"outputs": [],
|
578 |
+
"source": [
|
579 |
+
"# @title Build jitted functions, and possibly initialize random weights\n",
|
580 |
+
"\n",
|
581 |
+
"def construct_wrapped_graphcast(\n",
|
582 |
+
" model_config: graphcast.ModelConfig,\n",
|
583 |
+
" task_config: graphcast.TaskConfig):\n",
|
584 |
+
" \"\"\"Constructs and wraps the GraphCast Predictor.\"\"\"\n",
|
585 |
+
" # Deeper one-step predictor.\n",
|
586 |
+
" predictor = graphcast.GraphCast(model_config, task_config)\n",
|
587 |
+
"\n",
|
588 |
+
" # Modify inputs/outputs to `graphcast.GraphCast` to handle conversion to\n",
|
589 |
+
" # from/to float32 to/from BFloat16.\n",
|
590 |
+
" predictor = casting.Bfloat16Cast(predictor)\n",
|
591 |
+
"\n",
|
592 |
+
" # Modify inputs/outputs to `casting.Bfloat16Cast` so the casting to/from\n",
|
593 |
+
" # BFloat16 happens after applying normalization to the inputs/targets.\n",
|
594 |
+
" predictor = normalization.InputsAndResiduals(\n",
|
595 |
+
" predictor,\n",
|
596 |
+
" diffs_stddev_by_level=diffs_stddev_by_level,\n",
|
597 |
+
" mean_by_level=mean_by_level,\n",
|
598 |
+
" stddev_by_level=stddev_by_level)\n",
|
599 |
+
"\n",
|
600 |
+
" # Wraps everything so the one-step model can produce trajectories.\n",
|
601 |
+
" predictor = autoregressive.Predictor(predictor, gradient_checkpointing=True)\n",
|
602 |
+
" return predictor\n",
|
603 |
+
"\n",
|
604 |
+
"\n",
|
605 |
+
"@hk.transform_with_state\n",
|
606 |
+
"def run_forward(model_config, task_config, inputs, targets_template, forcings):\n",
|
607 |
+
" predictor = construct_wrapped_graphcast(model_config, task_config)\n",
|
608 |
+
" return predictor(inputs, targets_template=targets_template, forcings=forcings)\n",
|
609 |
+
"\n",
|
610 |
+
"\n",
|
611 |
+
"@hk.transform_with_state\n",
|
612 |
+
"def loss_fn(model_config, task_config, inputs, targets, forcings):\n",
|
613 |
+
" predictor = construct_wrapped_graphcast(model_config, task_config)\n",
|
614 |
+
" loss, diagnostics = predictor.loss(inputs, targets, forcings)\n",
|
615 |
+
" return xarray_tree.map_structure(\n",
|
616 |
+
" lambda x: xarray_jax.unwrap_data(x.mean(), require_jax=True),\n",
|
617 |
+
" (loss, diagnostics))\n",
|
618 |
+
"\n",
|
619 |
+
"def grads_fn(params, state, model_config, task_config, inputs, targets, forcings):\n",
|
620 |
+
" def _aux(params, state, i, t, f):\n",
|
621 |
+
" (loss, diagnostics), next_state = loss_fn.apply(\n",
|
622 |
+
" params, state, jax.random.PRNGKey(0), model_config, task_config,\n",
|
623 |
+
" i, t, f)\n",
|
624 |
+
" return loss, (diagnostics, next_state)\n",
|
625 |
+
" (loss, (diagnostics, next_state)), grads = jax.value_and_grad(\n",
|
626 |
+
" _aux, has_aux=True)(params, state, inputs, targets, forcings)\n",
|
627 |
+
" return loss, diagnostics, next_state, grads\n",
|
628 |
+
"\n",
|
629 |
+
"# Jax doesn't seem to like passing configs as args through the jit. Passing it\n",
|
630 |
+
"# in via partial (instead of capture by closure) forces jax to invalidate the\n",
|
631 |
+
"# jit cache if you change configs.\n",
|
632 |
+
"def with_configs(fn):\n",
|
633 |
+
" return functools.partial(\n",
|
634 |
+
" fn, model_config=model_config, task_config=task_config)\n",
|
635 |
+
"\n",
|
636 |
+
"# Always pass params and state, so the usage below are simpler\n",
|
637 |
+
"def with_params(fn):\n",
|
638 |
+
" return functools.partial(fn, params=params, state=state)\n",
|
639 |
+
"\n",
|
640 |
+
"# Our models aren't stateful, so the state is always empty, so just return the\n",
|
641 |
+
"# predictions. This is requiredy by our rollout code, and generally simpler.\n",
|
642 |
+
"def drop_state(fn):\n",
|
643 |
+
" return lambda **kw: fn(**kw)[0]\n",
|
644 |
+
"\n",
|
645 |
+
"init_jitted = jax.jit(with_configs(run_forward.init))\n",
|
646 |
+
"\n",
|
647 |
+
"if params is None:\n",
|
648 |
+
" params, state = init_jitted(\n",
|
649 |
+
" rng=jax.random.PRNGKey(0),\n",
|
650 |
+
" inputs=train_inputs,\n",
|
651 |
+
" targets_template=train_targets,\n",
|
652 |
+
" forcings=train_forcings)\n",
|
653 |
+
"\n",
|
654 |
+
"loss_fn_jitted = drop_state(with_params(jax.jit(with_configs(loss_fn.apply))))\n",
|
655 |
+
"grads_fn_jitted = with_params(jax.jit(with_configs(grads_fn)))\n",
|
656 |
+
"run_forward_jitted = drop_state(with_params(jax.jit(with_configs(\n",
|
657 |
+
" run_forward.apply))))"
|
658 |
+
]
|
659 |
+
},
|
660 |
+
{
|
661 |
+
"cell_type": "markdown",
|
662 |
+
"metadata": {
|
663 |
+
"id": "VBNutliiCyqA"
|
664 |
+
},
|
665 |
+
"source": [
|
666 |
+
"# Run the model\n",
|
667 |
+
"\n",
|
668 |
+
"Note that the cell below may take a while (possibly minutes) to run the first time you execute them, because this will include the time it takes for the code to compile. The second time running will be significantly faster.\n",
|
669 |
+
"\n",
|
670 |
+
"This use the python loop to iterate over prediction steps, where the 1-step prediction is jitted. This has lower memory requirements than the training steps below, and should enable making prediction with the small GraphCast model on 1 deg resolution data for 4 steps."
|
671 |
+
]
|
672 |
+
},
|
673 |
+
{
|
674 |
+
"cell_type": "code",
|
675 |
+
"execution_count": null,
|
676 |
+
"metadata": {
|
677 |
+
"cellView": "form",
|
678 |
+
"id": "7obeY9i9oTtD"
|
679 |
+
},
|
680 |
+
"outputs": [],
|
681 |
+
"source": [
|
682 |
+
"# @title Autoregressive rollout (loop in python)\n",
|
683 |
+
"\n",
|
684 |
+
"assert model_config.resolution in (0, 360. / eval_inputs.sizes[\"lon\"]), (\n",
|
685 |
+
" \"Model resolution doesn't match the data resolution. You likely want to \"\n",
|
686 |
+
" \"re-filter the dataset list, and download the correct data.\")\n",
|
687 |
+
"\n",
|
688 |
+
"print(\"Inputs: \", eval_inputs.dims.mapping)\n",
|
689 |
+
"print(\"Targets: \", eval_targets.dims.mapping)\n",
|
690 |
+
"print(\"Forcings:\", eval_forcings.dims.mapping)\n",
|
691 |
+
"\n",
|
692 |
+
"predictions = rollout.chunked_prediction(\n",
|
693 |
+
" run_forward_jitted,\n",
|
694 |
+
" rng=jax.random.PRNGKey(0),\n",
|
695 |
+
" inputs=eval_inputs,\n",
|
696 |
+
" targets_template=eval_targets * np.nan,\n",
|
697 |
+
" forcings=eval_forcings)\n",
|
698 |
+
"predictions"
|
699 |
+
]
|
700 |
+
},
|
701 |
+
{
|
702 |
+
"cell_type": "code",
|
703 |
+
"execution_count": null,
|
704 |
+
"metadata": {
|
705 |
+
"cellView": "form",
|
706 |
+
"id": "ft298eZskHtn"
|
707 |
+
},
|
708 |
+
"outputs": [],
|
709 |
+
"source": [
|
710 |
+
"# @title Choose predictions to plot\n",
|
711 |
+
"\n",
|
712 |
+
"plot_pred_variable = widgets.Dropdown(\n",
|
713 |
+
" options=predictions.data_vars.keys(),\n",
|
714 |
+
" value=\"2m_temperature\",\n",
|
715 |
+
" description=\"Variable\")\n",
|
716 |
+
"plot_pred_level = widgets.Dropdown(\n",
|
717 |
+
" options=predictions.coords[\"level\"].values,\n",
|
718 |
+
" value=500,\n",
|
719 |
+
" description=\"Level\")\n",
|
720 |
+
"plot_pred_robust = widgets.Checkbox(value=True, description=\"Robust\")\n",
|
721 |
+
"plot_pred_max_steps = widgets.IntSlider(\n",
|
722 |
+
" min=1,\n",
|
723 |
+
" max=predictions.dims[\"time\"],\n",
|
724 |
+
" value=predictions.dims[\"time\"],\n",
|
725 |
+
" description=\"Max steps\")\n",
|
726 |
+
"\n",
|
727 |
+
"widgets.VBox([\n",
|
728 |
+
" plot_pred_variable,\n",
|
729 |
+
" plot_pred_level,\n",
|
730 |
+
" plot_pred_robust,\n",
|
731 |
+
" plot_pred_max_steps,\n",
|
732 |
+
" widgets.Label(value=\"Run the next cell to plot the predictions. Rerunning this cell clears your selection.\")\n",
|
733 |
+
"])"
|
734 |
+
]
|
735 |
+
},
|
736 |
+
{
|
737 |
+
"cell_type": "code",
|
738 |
+
"execution_count": null,
|
739 |
+
"metadata": {
|
740 |
+
"cellView": "form",
|
741 |
+
"id": "_tTdx6fmmj1I"
|
742 |
+
},
|
743 |
+
"outputs": [],
|
744 |
+
"source": [
|
745 |
+
"# @title Plot predictions\n",
|
746 |
+
"\n",
|
747 |
+
"plot_size = 5\n",
|
748 |
+
"plot_max_steps = min(predictions.dims[\"time\"], plot_pred_max_steps.value)\n",
|
749 |
+
"\n",
|
750 |
+
"data = {\n",
|
751 |
+
" \"Targets\": scale(select(eval_targets, plot_pred_variable.value, plot_pred_level.value, plot_max_steps), robust=plot_pred_robust.value),\n",
|
752 |
+
" \"Predictions\": scale(select(predictions, plot_pred_variable.value, plot_pred_level.value, plot_max_steps), robust=plot_pred_robust.value),\n",
|
753 |
+
" \"Diff\": scale((select(eval_targets, plot_pred_variable.value, plot_pred_level.value, plot_max_steps) -\n",
|
754 |
+
" select(predictions, plot_pred_variable.value, plot_pred_level.value, plot_max_steps)),\n",
|
755 |
+
" robust=plot_pred_robust.value, center=0),\n",
|
756 |
+
"}\n",
|
757 |
+
"fig_title = plot_pred_variable.value\n",
|
758 |
+
"if \"level\" in predictions[plot_pred_variable.value].coords:\n",
|
759 |
+
" fig_title += f\" at {plot_pred_level.value} hPa\"\n",
|
760 |
+
"\n",
|
761 |
+
"plot_data(data, fig_title, plot_size, plot_pred_robust.value)\n"
|
762 |
+
]
|
763 |
+
},
|
764 |
+
{
|
765 |
+
"cell_type": "markdown",
|
766 |
+
"metadata": {
|
767 |
+
"id": "Pa78b64bLYe1"
|
768 |
+
},
|
769 |
+
"source": [
|
770 |
+
"# Train the model\n",
|
771 |
+
"\n",
|
772 |
+
"The following operations require a large amount of memory and, depending on the accelerator being used, will only fit the very small \"random\" model on low resolution data. It uses the number of training steps selected above.\n",
|
773 |
+
"\n",
|
774 |
+
"The first time executing the cell takes more time, as it include the time to jit the function."
|
775 |
+
]
|
776 |
+
},
|
777 |
+
{
|
778 |
+
"cell_type": "code",
|
779 |
+
"execution_count": null,
|
780 |
+
"metadata": {
|
781 |
+
"cellView": "form",
|
782 |
+
"id": "Nv-u3dAP7IRZ"
|
783 |
+
},
|
784 |
+
"outputs": [],
|
785 |
+
"source": [
|
786 |
+
"# @title Loss computation (autoregressive loss over multiple steps)\n",
|
787 |
+
"loss, diagnostics = loss_fn_jitted(\n",
|
788 |
+
" rng=jax.random.PRNGKey(0),\n",
|
789 |
+
" inputs=train_inputs,\n",
|
790 |
+
" targets=train_targets,\n",
|
791 |
+
" forcings=train_forcings)\n",
|
792 |
+
"print(\"Loss:\", float(loss))"
|
793 |
+
]
|
794 |
+
},
|
795 |
+
{
|
796 |
+
"cell_type": "code",
|
797 |
+
"execution_count": null,
|
798 |
+
"metadata": {
|
799 |
+
"cellView": "form",
|
800 |
+
"id": "mBNFq1IGZNLz"
|
801 |
+
},
|
802 |
+
"outputs": [],
|
803 |
+
"source": [
|
804 |
+
"# @title Gradient computation (backprop through time)\n",
|
805 |
+
"loss, diagnostics, next_state, grads = grads_fn_jitted(\n",
|
806 |
+
" inputs=train_inputs,\n",
|
807 |
+
" targets=train_targets,\n",
|
808 |
+
" forcings=train_forcings)\n",
|
809 |
+
"mean_grad = np.mean(jax.tree_util.tree_flatten(jax.tree_util.tree_map(lambda x: np.abs(x).mean(), grads))[0])\n",
|
810 |
+
"print(f\"Loss: {loss:.4f}, Mean |grad|: {mean_grad:.6f}\")"
|
811 |
+
]
|
812 |
+
},
|
813 |
+
{
|
814 |
+
"cell_type": "code",
|
815 |
+
"execution_count": null,
|
816 |
+
"metadata": {
|
817 |
+
"cellView": "form",
|
818 |
+
"id": "J4FJFKWD8Loz"
|
819 |
+
},
|
820 |
+
"outputs": [],
|
821 |
+
"source": [
|
822 |
+
"# @title Autoregressive rollout (keep the loop in JAX)\n",
|
823 |
+
"print(\"Inputs: \", train_inputs.dims.mapping)\n",
|
824 |
+
"print(\"Targets: \", train_targets.dims.mapping)\n",
|
825 |
+
"print(\"Forcings:\", train_forcings.dims.mapping)\n",
|
826 |
+
"\n",
|
827 |
+
"predictions = run_forward_jitted(\n",
|
828 |
+
" rng=jax.random.PRNGKey(0),\n",
|
829 |
+
" inputs=train_inputs,\n",
|
830 |
+
" targets_template=train_targets * np.nan,\n",
|
831 |
+
" forcings=train_forcings)\n",
|
832 |
+
"predictions"
|
833 |
+
]
|
834 |
+
}
|
835 |
+
],
|
836 |
+
"metadata": {
|
837 |
+
"colab": {
|
838 |
+
"name": "GraphCast",
|
839 |
+
"private_outputs": true,
|
840 |
+
"provenance": [],
|
841 |
+
"toc_visible": true
|
842 |
+
},
|
843 |
+
"kernelspec": {
|
844 |
+
"display_name": "Python 3",
|
845 |
+
"name": "python3"
|
846 |
+
},
|
847 |
+
"language_info": {
|
848 |
+
"name": "python"
|
849 |
+
}
|
850 |
+
},
|
851 |
+
"nbformat": 4,
|
852 |
+
"nbformat_minor": 0
|
853 |
+
}
|
setup.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 DeepMind Technologies Limited.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS-IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
"""Module setuptools script."""
|
15 |
+
|
16 |
+
from setuptools import setup
|
17 |
+
|
18 |
+
description = (
|
19 |
+
"GraphCast: Learning skillful medium-range global weather forecasting"
|
20 |
+
)
|
21 |
+
|
22 |
+
setup(
|
23 |
+
name="graphcast",
|
24 |
+
version="0.1",
|
25 |
+
description=description,
|
26 |
+
long_description=description,
|
27 |
+
author="DeepMind",
|
28 |
+
license="Apache License, Version 2.0",
|
29 |
+
keywords="GraphCast Weather Prediction",
|
30 |
+
url="https://github.com/deepmind/graphcast",
|
31 |
+
packages=["graphcast"],
|
32 |
+
install_requires=[
|
33 |
+
"cartopy",
|
34 |
+
"chex",
|
35 |
+
"colabtools",
|
36 |
+
"dask",
|
37 |
+
"dm-haiku",
|
38 |
+
"dm-tree",
|
39 |
+
"jax",
|
40 |
+
"jraph",
|
41 |
+
"matplotlib",
|
42 |
+
"numpy",
|
43 |
+
"pandas",
|
44 |
+
"rtree",
|
45 |
+
"scipy",
|
46 |
+
"trimesh",
|
47 |
+
"typing_extensions",
|
48 |
+
"xarray",
|
49 |
+
],
|
50 |
+
classifiers=[
|
51 |
+
"Development Status :: 3 - Alpha",
|
52 |
+
"Intended Audience :: Science/Research",
|
53 |
+
"License :: OSI Approved :: Apache Software License",
|
54 |
+
"Operating System :: POSIX :: Linux",
|
55 |
+
"Programming Language :: Python :: 3.10",
|
56 |
+
"Programming Language :: Python :: 3.11",
|
57 |
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
58 |
+
"Topic :: Scientific/Engineering :: Atmospheric Science",
|
59 |
+
"Topic :: Scientific/Engineering :: Physics",
|
60 |
+
],
|
61 |
+
)
|