Building Simulations that Scale
ETHCC 7 · 10 Jul 2024 · 22:33
Benjamin Scholtz, head of engineering at CAD Labs, explains how to build token engineering simulations that scale, using cadCAD and its variant RADCAD. He shows how state history, immutability, deep copies and data classes slow a simulation, and why profiling should run early, even in CI. A Game of Life benchmark compares native Python, Numba, NumPy, GPU and multiprocessing. He also covers representative agents, Parquet and Dask for large data, and moving runs to the cloud with Ray.
Speakers
Topics
From ETHCC 7, hosted by Ethereum France.
Transcript
Scale. Welcome. Thanks, Angela. Cool. So yeah, most of the talks today have been focused on simulation theory or the theory of token engineering. I'm going to be focusing on methodology. So it's going to be a little bit more of a technical presentation. I'm going to assume some level of programming knowledge. But yeah, basically going to try and motivate why building simulations that scale is very important. Often it's an afterthought. And you know, then we get clients coming to us and asking, we want to introduce uh agents, we want to introduce uh larger sort of simulations with more scenarios, and uh it becomes very difficult to backtrack and to improve the performance of your simulation.
So yeah, I'm the head of engineering at CAD labs, and uh. So CAD labs is basically we we're a web three systems engineering firm. We specialize in CAD or computer-aided design of uh Web3 protocols. And uh one of the tools that we use is software modeling and simulation. Um probably best known for our work uh on CADCAD.education, which was a collaboration with the Ethereum Foundation and the Robust Incentives Group to create a sort of open source educational software model, and uh we also do work in um research, quantitative mechanism design, and risk modeling and decision support tooling. So personally, I've got a background in control systems engineering.
Uh I originally started working on s uh simulation in in MATLAB and uh yeah, it feels uh amazing to to come here and present on sort of similar topics at uh a cryptocurrency uh token engineering conference. Um the goals of the simulation, we want to understand the different stages of the modeling and simulation process, make you know to make you appreciate what makes it challenging to create a scalable simulation, and walk away with a toolbox of profiling and optimization tools and techniques. Some of the topics will be about the workflow, the framework, specifically CADCAD and the variation RADCAD which we built, simulation profiling and optimization, and finally taking those to production in the cloud.
We're going to use a basic sort of game as a way to demonstrate this to make it a little bit more approachable. So even if you're not familiar with CADCAD, you should still appreciate what we will be presenting today. Cool. So quickly a show of hands, who's familiar with this scenario? You know, waiting for your code to compile, your simulation to complete. Just to get an idea of what the type of audience I'm dealing with. Okay, cool. Cool number of you. Great. So yeah, I mean, I think I spoke to a couple people before this presentation, and uh what is a large simulation? So you know, it could uh basically anything that's larger than consumer uh hardware.
So if if you're struggling to run it on your MacBook M1 uh laptop and you need to you know find alternative um solutions to scale that simulation, that's that's where this the topics today will come in. Um, where does this fit into the engineering design process? So the engineering design process starts with uh uh a large sort of basis, which is system requirements gathering. Uh so here we would be doing requirement specification for the software, the business and technical requirements, and then where simulation comes in is is later on once you've uh designed a software model and you now want to do um simulation experiments, so that's in that uh third tier over there. And finally, decision support tools.
There's a lot of performance considerations as well in that process, trying to get a data analysis analysis that is responsive to users so that they can change parameters, see what's going on. Personally, I'm I'm quite passionate about the role that simulation and modeling as well plays in education. And yeah, so we'll we'll go into that a little bit later as well. So, first of all, the data intensive applications. This is a term that was uh coined by Martin Kleppermann. He's got a book called Designing Data Intensive Applications, we could recommend it as a to read.
Um so basically they rely heavily on data processing, storage, and retrieval rather than computational um requirements. But uh yeah, in the case of simulation, I think it's both, but specifically we're gonna be focusing on data today because that's where most of the bottlenecks come in. So, what what makes a simulation performant, right? It's not just about the speed, it's also about the scalability. So, for example, if you increase the size of your dimensions, how quickly does the performance degrade, for example? Um, resource efficiency, so uh how efficiently is it using whatever resources you have available to you, your memory, your CPU, for example, and then all the way through to interactivity, as I as I mentioned with decision support tooling, how responsive it is to to users' input.
Cool. So, about simulation frameworks. Um, we specifically are going to be talking about a framework called CADCAD. It was uh created by Block Science, it's a sort of dynamical systems simulation framework. It's it's quite general purpose. So often the alternative will be you know implementing your own framework in, for example, academic or research fields, or using something like MATLAB or alternatives where it's sort of proprietary software and often a sort of visual diagram software simulation tool. Okay, so it's a framework for simulation.
So on the left hand side, you've basically got one time step, which is that big loop around the top. So a time step could be a block in the case of a blockchain, it could be block time. You could do uh sort of low resolution, for example, daily, and what you have is your state variables in the blue block on the left, and they will evolve over time. So, what you're doing is you're basically defining these state update functions. Uh here we've got an example where we have three state update functions. Uh these aren't actually executed in parallel in the case of CADCAD. Um, and we'll we'll get into some of those considerations later.
But um, yeah, basically you you evolve a state over time, and then on the right hand side you introduce things like policies, which is um when and how should these uh state updates be performed. Uh, you know, this this could be some sort of governance policy or whatever you decide that logic should be. So speed and scalability, they're a function of these dimensions. Um so you need to be thinking about this early on, right? If you if you know you want to do an agent-based simulation, a pure agent-based simulation, not um you know, an aggregate sort of agent-based model, then you need to to understand that uh the performance is going to be a function of the number of agents in this simulation. Um, if you're doing Monte Carlo runs, uh you you need to make sure that you're going to possibly be able to parallelize those runs when you're executing that simulation and uh in the end um yeah state's got a little bit explanation mark there because it's it's often the biggest bottleneck what is what are your data structures look like um how much uh memory is that using and uh simulation is all about you know mutating and and moving these these uh data structures uh over time so it's uh that's why for example a MacBook M1 it's got a unified memory it's because it's got a memory sort of very close to the CPU and uh that's particularly good for simulations and uh yeah it's just something to keep in mind if you're looking for a sort of uh a local simulation um tool so you start with state for example you know a set a set of agents you introduce substeps sub steps so you know multiple state updates in a single simulation time step and now you've got uh three times the amount of data potentially um as soon as you introduce time steps you you now have that uh state multiplied by the number of time steps so if you want to do one year five years at you know 15 minute resolution can quickly scale up you have different subsets so for example you want to do an A B test you want to test two different sets of parameters and now you've once again uh potentially yeah multiplied the the size of the state that you're working with and finally runs if you wanted to start doing Monte Carlo runs then it just the the size of that simulation increases um once again.
So, what are the different questions you can ask yourself to try and manage this? You don't always need the full state history. You could take uh a subset or just the final metrics and KPIs. Um, it's it's always a little bit of a compromise if you if you start uh you know calculating your metrics during runtime, you can maybe get rid of a whole lot of that data that you're storing during the simulation, but um you might slow down the simulation. Um, whereas if you decide okay, you want to do all your post-processing right at the end, you might improve the speed of your simulation, but slow down the the speed of your post-processing. So these are all things that um you need to keep in mind.
So we're gonna go through a basic example now. We're going to build up a basic simulation framework. Um so basically you what you need is uh a state that you're gonna update or a certain number of time steps, potentially you're gonna introduce a parameter sweep where you are changing um some parameter of the model that the model depends on, and finally executing that a certain number of times if you've got some sort of um random process. So first step, we've got time step, state, state updates. It's very simple, it's not very useful.
Uh it's yeah, I guess performance, it's you know operating about 77 microseconds. Um now we you know we at at least need state history so that you at the end of the simulation you can see how has that state changed over time. Um otherwise you're just gonna see what is the the final state. As soon as you introduce state history, you can see it's about 1.6 times slower. This is this sort of memory bottleneck being introduced. Um you're now storing that that state history, you're potentially accessing it during the simulation. If you want to ensure immutability.
Now it's 3.4 times slower than the last implementation we had. Um and uh you can see once again it's it's a it's a uh condition of of memory. So you you to ensure immutability, you basically have to create a deep copy of that data structure to make sure that you have that original data available to you. And then yeah, this is this is one of the most common problems we run into. So what data type are you choosing? So you know, a data class is very convenient, it's it's a nice modular data structure, you can introduce types, but the performance impact can be fairly significant depending on how you're using them.
So if you're having to create multiple agents or multiple positions, if those you know agents are opening positions on a DeFi protocol, that 4.6x is uh you know the the creation time compared to a basic dictionary. Um another issue with the things like data classes is that you can't use uh some of some libraries, for example, like number or uh you know potentially numpy could even be a better solution if you're using um calculations that can be vectorized. Uh so it's it's it's yeah, you you need to know early on uh what the scale of your simulation is so you can make these decisions early and not have to refactor at a later date.
And finally, runs in parameter sweep, so now we've got a basic simulation framework that we can play with. Cool. So this this next topic is going to be about simulation profiling. Uh it's something that you you need to do quite early on in in the simulation process. Um it's yeah, as I said earlier, if if you get to a point where you find out that your simulation is not performant, it's very difficult to actually figure out exactly what is it that caused that performance issue. Whereas if you had profiling from the very beginning, potentially in your CI CD pipeline, you'll know, okay, we made this code change, the simulation is is suddenly 2x slower, and uh you can deal with it. So it needs to support the following considerations.
You know, what is your methodology that you're using, what are the dimensions of your simulation and scalability as well. So testing uh is your simulation scaling well as you increase the dimensions of your simulation. And yeah, it's a compromise, right? So each decision is going to impact the performance of future stages. Um so initially during runtime you you worry mostly about time and memory, those are the easiest things to measure. Um in pre- and post-processing, you might worry about data read speed, you know, where is your data being stored? Is it a big uh multi-gigabyte CSV file or is it a parquet file that can be more efficiently accessed?
Um and then finally in visualization, it's how quickly can you generate those visualizations? Um are you reducing the the data to be able to visualize uh those sort of questions. And profiling can also slow down your code, so you need to use it wisely. Cool. So this is a standard sort of um uh CICD pipeline test that we include in all our software models and simulations. It just makes sure that uh if there's a regression in the performance, you know about it uh before the code is merged. Um you can check that out on the public repo link there.
And time profiling, so you can perform this at different levels. Uh so you know, end-to-end, how long is your simulation? Uh you can profile specific functions within your simulation, and you get sort of different visualizations that you can see on the right hand side there. Um, one where it breaks down the sort of uh cool percentage allocation of the different methods. Um ideally you want to see some sort of consistent linear growth. In practice, it's it's a little bit more uh haphazard on as on the right hand side there.
Cool. The next phase simulation optimization. So we're going to look at a basic example. It's game of life. It's got four very simple rules about basically the the birth and death of these basic agents in a in a grid. It's a good example to use for simulation because it's uh very data intensive, and so it you can apply some of the techniques of optimization. Okay, so the the contenders for this are going to be a native Python implementation. We're going to use different Python libraries that you can use out the box for optimization of performance, such as number and numpy, and uh taking a look at different multi-processing methods.
So the Python implementation is uh quite complex, but with a couple of lines of code, you can basically do just in time compilation, and uh you'll see in a moment uh what sort of performance improv improvements you can see. Um with number, you can also execute on the GPU. So once again, it's an out the box library, and with a few lines of code change, you can move that that execution into the GPU. And with NumPy, it's a sort of significant refactor and uh arguably more complex and less readable.
And yeah, state update optimization. So what about the actual loops? So the runs, for example. There are different ways that you can execute those runs in in series or in parallel, for example. Radcat is a number of different options, for example, doing distributed computing in the cloud. And that's what the implementation looks like. Okay, so the experiment was basically eight different implementations, 100 time steps, a sweep of one and ten runs, different grid sizes. So that changes the sort of size of the state that we're dealing with.
And we executing that on Google Colab where they give you access to free GPU time if you want to run this yourself afterwards. I'll share the notebook. Okay. So we can see that the native Python implementation quickly loses and is only saved by multi-processing. So in the case of multi-processing, it does also introduce significant uh overhead. So for an implementation like number on the GPU, it's it doesn't in fact introduce uh performance gain, but for slower running implementation, for example, using number, it uh does introduce a significant improvement. And uh the results of our efforts are game of life simulation.
Cool. So uh rule of thumb, choose number if your code is lots of loops or complex numerical calculations. Uh numpy, if you need to perform operations on arrays and matrices. And choose local parallel processing if your operations are independent and CPU bound. And you can choose remote distributing, distributed computing if the sort of requirements exceed the capabilities of a single machine. Cool. So a question we often get is you know, why can't we just use an agent-based modeling model?
They're particularly difficult to optimize. So in the case of an agent-based model, it's sort of bottom up, it's emergent behavior. You don't need to define the rules explicitly in a mathematical calculation, for example. Whereas the system dynamics model, you are defining you know the economic rules of the system, not necessarily with individual agents taking different actions. So yeah, with an ABM, that's it also you have alternatives like having representative agent models. Uh so you don't need to have hundreds of thousands of agents if you assume your protocol will have hundreds of thousands of agents.
You can have different categories of agents, and that will help you improve the performance of your simulation. Cool. So uh how are we doing for time? Cool. Um, so yeah, we we've also got different ways to basically decompose calculations so that they can be parallelized. Typically, this is spatial or functional decomposition. Uh, this is not always possible, um particularly in token engineering contexts. Uh, you know, it's not all it's rarely, if ever that you have spatial uh problems, whereas um functional problems you can in some in some cases uh parallelize your state update functions.
Um so RADCAD has different features that allow you to basically hook into the simulation and manipulate the way that it operates. You can change the way the way or which objects are basically immutable by using a different deep copy method. You can also dump your state to disk at certain points in time to get it out of memory. And finally, you can do different operations after a time step, for example, trying to manually uh call the garbage collector in the case of Python. So in the case where you have data that's greater than memory, Parquet and DASC are great solutions.
It enables you to basically use a column-based data structure, which allows you to more efficiently sort of reduce the size of a data set before you do your calculations. Visualization performance, as I said, is another key consideration. The different things you can do here, you can pre-compute your results, you can downsample to reduce the dataset size. And this last little bit is quite quick. What do you do once you want to move it into production? When are you ready for the for the clouds?
So this really should only be for validation of very large simulations. It's quite a time consuming process to move your simulation to the cloud, to manage the data in the cloud, etc. There are different tools out of the box that you can use for this. KML is a good one. It's open source and has a sort of software as a service solution that allows you to track your experiments and manage the results of your experiments more easily. So high performance computing, it can be complex, like in this example over here, but it doesn't have to be. So for example, uh, we were looking at Ray earlier.
If you're using Ray to paralyze your runs locally, you can with a couple of lines of code parallelize those uh in the cloud. And the same with Dask and post-processing. If you're using parquet files and DASC, you can in a couple of lines of code move that into the cloud. Okay. And uh finally accessing your simulations once they're running in the cloud. Uh there are different ways to do this. My sort of preferred choice is using something like VS Code, uh, where you have a remote, yeah, remote uh it's a sort of extension that allows you to access your code remotely and execute it, and then using sort of a Jupyter Notebook server that you access locally. Cool.
So in summary, plan for the dimensions of your simulation, profile early and often. Uh it's it's often a compromise, um, but there are some quick wins. And uh yeah, it's more accessible than ever. High performance computing and distributed computing, uh all available out of the box these days. Um there's no one size fits all, so you need to experiment, but I think that's half of the fun of it. And uh yeah, if you want to get in touch with me, contact at Ben at Cadlabs.org and we'll share the Google Notebook in this presentation afterwards. Thank you.
Awesome. Thank you so much, and I think next for the next token engineering track, we should dedicate a whole afternoon on simulations and optimizations.
Related talks
- [UNCHAINED LIVE] The Fight Over TestNet ETH: Scarce, Tradeable Commodity or Public Good?
- Compositionality: The 10x Engineer Secret Sauce | Devcon Bogotá
- Learnings from FOAM Location Developer Stack
- Interview with Piper Merriam of Ethereum Alarm Clock at DEVCON1 in London
- Initiation to DeFi with the GTON Capital Team (for Traders, VCs and non-devs)
- GMX Perpetuals Trading
- Pocket Network V1 Hello Block Daniel Olshansky
- Eva Beylin, Yaniv Tal : Decentralization in Practice via The Graph
- Juan Benet - Building Web3: Filecoin + Ethereum Better Together