I’ve enjoyed writing this blog – and it’s moving! I’m going to be publishing under my real name on jsmallwood.net
Come on over to continue reading!
I’ve enjoyed writing this blog – and it’s moving! I’m going to be publishing under my real name on jsmallwood.net
Come on over to continue reading!
In How To Beat Your Dad At Camel Up (Part 4 – Reinforcement Learning) we looked at training a reinforcement learning agent to learn to play Camel Up. There was a problem. Our agent was getting too bogged down in the details! Today, we’re going to fix this and help the agent learn 120 times faster!
I mentioned in the previous article that the agent’s state space was too large, which would mean that the agent would not learn well. This is because the agent matches the exact game state it’s observing to a row in its table and looks up the best action to take. If the number of rows in the table is too large, then it will have trouble populating them meaningfully.
The underlying problem is that our representation of the game state has too many possible values. The information we’re tracking is too specific. We’re passing a list of the spaces each camel is on. For instance, red is on space 2, blue is on space 3, and so on. This meant that the number of options had an upper bound of , which is huge!
I realized that the best action given a board state is fundamentally the same whether blue is leading or red is leading. If a camel is way out in front, I’m going to bet on it. It doesn’t matter the color! Using this idea, we can alter the representation of the state space to remove color, which will make the agent’s job a lot easier.
Let’s compare the old and the new approaches:
The old representation
We used a system with an array specifying the space on the track for each camel, where the first element is always the red camel’s position, for example. There’s also been a secondary array telling us the ordering of the stacks of the camels on the board. We also have arrays telling us which dice have been rolled, and which betting tiles are available.
An example is:
The new system
We use an array where the first element is the board space of the camel in first place, the second the board space of the camel in second place, and so forth. This will intrinsically also tell us information about the stacks on the board. For example, if the array is [3, 3, 2, 2, 1] then we know that there are two stacks, one on space 3 containing 2 camels, and one on space 2 containing 2 camels.
We then need another array telling us which camel is in which position to fully know the board state. For decision-making purposes, it doesn’t matter whether the first camel is red, or blue. If you just want to bet on the camel currently leading, it doesn’t matter what color is it!
An example is:
The agent doesn’t need the “Order of Camels” array to make its action choice. Therefore, the state space should then be smaller by a factor of 5! = 120 which removes the information about which camel is which.
How many states in this representation?
So how many different board states are there in this representation? Let’s have a look. It’s always good to do something two ways and check you get the same answer! We’re going to do a brute-force method and a combinatorics approach. We should get the same answer each way.
Brute Force!
We’re going to try to count all the possible states and sum them up. The argument goes:
Converting this to summations, the number of combinations is:
We can evaluate this sum using Python. Remember that the range(1, 17) operator will evaluate 1 through 16, it does not evaluate the upper limit:
sum = 0
for i in range(1,17):
for j in range(1, i + 1):
for k in range(1, j+1):
for m in range(1, k+1):
for n in range(1, m+1):
sum += 1
print(sum)
This gives us the answer of 15,504 combinations.
Let’s derive this analytically as well. I’ll sketch the proof and give all the other results you need to complete it. The algebra will be left as an exercise for the reader (I’ve always wanted to say that).
You then expand the expression and get a sum of squares term and a sum of integers term. To complete the simplification you’ll need the following series expressions:
Using the final expression is
.
If you substitute in then this formula agrees with the solution of 15,504 combinations.
Combinatorics!
If we massage the formula above this will turn into something interesting. Firstly note that , and with 5 camels on the board, this is the combination formula for
.
How does this make sense? Well, a board with spaces can be shown using
borders, which I’ll denote by |. I’ll denote camels with an x. For example, if I have two spaces, then a camel can be on the first space as x|, or on the second space as |x. So one | demarcates two spaces on the board. Similarly, 5 spaces can be shown using 4 |, and 16 spaces with 15 |. This means that
spaces on the board can be shown with
copies of |.
We also have 5 camels to place on the board, and they can be on a space or in a stack with other camels. The board state can be shown using a string of |s and xs. For example, |||xx||xxx||||||||||| shows a board state with two camels stacked on space 4, and three camels stacked on space 6. The number of possible states becomes the number of different ways we can order this collection of symbols, which is . If we substitute in
then this also gives us
.
So, both of our arguments give us the answer 15,504 for the number of possible camel position combinations. Not all of these will be achievable, for example it’s not possible in the game mechanics to have 4 camels on space 16 and 1 camel on space 1. This is an upper bound for the possible states.
What’s Next?
In the next article, we’ll apply this to our reinforcement learning model and see how it improves! We should see a marked improvement in our performance. We’ll also apply some other optimizations to get our AI agent beating us in no time!
I had the privilege of attending PyCon AU in Melbourne over the 22nd-24th November 2024. After my experience at PyCon US I was excited to attend the Australian version for the first time. In this article I’ll discuss my experience, how it compared to the US version, and some constructive feedback for the PyCon AU team.
Where: Melbourne Exhibition & Convention Center.
When: 22nd – 24th November 2024.
I attended talks on Friday and Saturday morning. Due to other commitments and a very sick cat, I wasn’t able to attend the whole conference.
Talks
The talks I saw were extremely high quality. My highlights were:
Volunteering
I’m a big proponent of throwing your hat in the ring to volunteer to get the most out of your PyCon experience. It’s the best way to meet new people, have great conversations, and give back to the community. At PyCon US I worked the registration desk for a few hours, and I thought this time I’d try out session chairing. As a session chair I was responsible for introducing and thanking the speakers, giving them timing cues, facilitating Q&A, and ensuring the session ran close to schedule. I chaired the Saturday morning session in the Goldfields Theatre and it was an awesome experience that I will definitely sign up for again!
My experiences volunteering have been extremely positive. Don’t be afraid to put up your hand when the opportunity arises.
General Experience
The Melbourne Convention Center was a great choice for a venue, and there was a layer of polish on many parts of the conference. The talk intro cinematic was nifty, the food was great, and the talks were excellent. The organizing committee did a great job with so many parts of this conference.
While I have great respect for what was achieved, I do think there are some low-hanging fruit in terms of improving the attendee experience:
However, I think the most important change to improve the experience the most is creating more space for the birds-of-a-feather sessions or “open spaces”.
Birds-of-a-feather Sessions / Open Spaces
These sessions were my favourite part of PyCon US. For those unfamiliar, these are small unstructured sessions to discuss any topic they wish. I liked them because they were the place to actually meet people and have discussions. Talks are great for content, but meeting someone new at a talk is nigh impossible. At PyCon US, these ran every hour of the day and were co-ordinated through a large physical board. At AU – these were organized on the Discord. This was mostly people trying to organize, I didn’t see a lot of groups actually go ahead. Why are these sessions so important? Well, a conference where the talks will all go on YouTube afterwards needs to offer value to those attending in-person. These open spaces provide both an opportunity for networking and an experience that you can’t upload to YouTube. I understand the logistical issues involved with getting sufficient space for these to occur. There are also concerns about splitting the audience too much between open spaces and the talks. However, I think this is the best part of the PyCon experience and it deserves to be a first-class citizen.
Next time, PyCon AU should have a board like the US conference, and reserve some space for these to go ahead. Make it clear as well that it’s OK for these to run over the top of talks.

Next Steps
It’s easy to throw stones from the outside of a process, but it is harder to actually implement these suggestions. So, the question I ask myself is, what am I going to do about it? While it’s early to start thinking about PyCon AU 2025, I should start preparing myself to step up and help. Not only will this be a great way to get to know others and contribute, I think it will be an opportunity to shape space for Pythonistas in Australia to meet, collaborate, and learn.
Recently I’ve been spending a lot of time thinking about the board game Camel Up. If you’ve missed it – check out the series starting here: How to Beat Your Dad At Camel Up. One observation from my last article about reinforcement learning was that the number of game states is very large. This means our agent needs to play the game many millions of times to see all possible states. This led me to the question – how many board states, exactly, are there?
Why does this matter? Well, if we know how many states there are, we can target how many games to play during training. If the number is unreachable given our setup – it will also tell me if I must be smarter about updating the Q-table (expected future reward from an action given the game state).
Let’s start with some naive results. If we assume that:
then we have 17 options for each of the camels, so the number of combinations would be . Not all of these are possible combinations. For example, it’s not possible to have 4 camels on space 16 and one camel on space 1, as there are no combination of die rolls that results in that board state. It’s also dependent on the leg, it’s impossible to have camels on space 1 in the 5th leg. We’re going to call allowed board states admissible.
Definition: A board state is admissible if there is a possible sequence of legal moves that will produce that board state. If no such sequence exists then the board state is inadmissible.”
So we want to answer the question: how many admissible board states are there?
We’re not going to answer that exact question today. However, I want to lay out my thoughts on tackling this problem and present some initial work on a sub-problem.
There are some standard ways in mathematics to try to answer such a question:
To make a theoretical argument on which states are possible, it will be useful to understand how the camels move. For example, if we know there is no way for two camels to both move 16 spaces in one leg then we know that is an inadmissible board state on leg 1.
Let’s start with an easier sub-problem. Given a camel on a space, in how many ways can it move spaces in a leg? For example, a camel can move 1 space in 1 way, if it rolls a 1. It can move 2 spaces in 2 ways: if it rolls a 2, or if there is a camel underneath it that rolls a 1, and then our top camel rolls a 1. This is dependent on how many camels are potentially under the camel. If it is the only camel on the board, then it can only move a maximum of 3 spaces (and it’s guaranteed to win!). If there are 4 other camels that can potentially boost it up the board, then it can move significantly farther.
To put some nomenclature around this to make it easier – I’m going to refer to the camel that’s moving as the target camel. We are not conditioning on any game state, so this distribution will make no assumption on whether there is a camel underneath the target camel or not. We will refer to this as a possible camel.
We can derive a recurrence relationship for the number of ways the target camel can move using dynamic programming:
Definition: Let
be the number of ways a target camel can move
spaces with
possible camels underneath it.
I posit that the recurrence relationship to generate these is as follows:
That is, the number of ways for the target camel to move spaces is the number of ways for a possible camel underneath our target camel to move sufficient spaces so that our target camel can roll a one, two, or three to get to the desired space. The possible camel underneath can have at most one fewer possible camel underneath it, as we know our target camel is on top of the possible camel.
Given this, we can derive some initial conditions for and then use those to derive the entire distribution!
If there are no possible camels underneath our camel, then this camel can move 1, 2, or 3 spaces in exactly one way each. The only possible way is to roll that number on the die and move that many spaces. Therefore:
. For completeness,
for
and
for
.
We can now sort out the case, where there can be at most one possible camel. The target camel can still move 1 space in exactly 1 way, rolling a 1. However it can now move 2 spaces in 2 ways: rolling a 2, or a possible camel rolling a one followed by the target camel rolling a 1.
We illustrate by applying our recurrence formula for the case:
We can tabulate the higher values of using Python.
from collections import defaultdict
# Using a defaultdict to avoid having to check if value has been set.
output = defaultdict(lambda: defaultdict(int))
# Set c=0 values.
output[0][1] = 1
output[0][2] = 1
output[0][3] = 1
for c in range(1, 5):
for x in range(1, 17):
output[c][x] = output[c-1][x-3] + output[c-1][x-2] + output[c-1][x-1] + (1 if 1 <= x <= 3 else 0)
Running this code results in the distributions below:
| x / c | c = 0 | c=1 | c=2 | c=3 | c=4 |
| x=1 | 1 | 1 | 1 | 1 | 1 |
| x=2 | 1 | 2 | 2 | 2 | 2 |
| x=3 | 1 | 3 | 4 | 4 | 4 |
| x=4 | 3 | 6 | 7 | 7 | |
| x=5 | 2 | 8 | 12 | 13 | |
| x=6 | 1 | 8 | 18 | 23 | |
| x=7 | 6 | 22 | 37 | ||
| x=8 | 3 | 22 | 52 | ||
| x=9 | 1 | 17 | 62 | ||
| x=10 | 10 | 61 | |||
| x=11 | 4 | 49 | |||
| x=12 | 1 | 31 | |||
| x=13 | 15 | ||||
| x=14 | 5 | ||||
| x=15 | 1 |


We can see the peak of the distribution move to the right as increases. It also starts to look pretty bell-curvy. As
increases, the mean converges to
as shown on the graph below.

I’ve been unable to experimentally find a function for the standard deviation as increases. I’ve tried fitting a power law of various forms and nothing quite fits. I’ll continue to work on that one over the coming weeks.
In this article I’ve derived the distribution of the number of ways that a camel can move a number of spaces. This is not yet of much practical benefit for your game night! We’re much more interested in the distribution of the number of ways a camel can move given an initial game state. However, this is a first step.
Where am I hoping that this will lead? I’m hoping that this will help answer these questions:
Stay tuned for the next article to start figuring out the answers to these questions! Subscribe today so that you don’t miss an article.
Welcome back! I hope you enjoyed our session on CUDA! Missed it? Catch up here: How to Beat Your Dad At Camel Up (Part 3 – CUDA Baby!). If you’ve missed the whole series so far, start here: How to Beat Your Dad At Camel Up!
This is a continuation of our series on how to become a camel betting legend at your family games night. We’ve been using Python and C++ to dive deep into Camel Up over the last three articles. What’s new today? We’re going to harness the power of AI to play the game for us! How are we going to do that, you ask? We’re going to use reinforcement learning!
In this article I want to explain a little about reinforcement learning and how I’ve applied this to Camel Up. A word of warning – my agent won’t be conquering the world anytime soon. I clearly have a lot to learn! I do hope that this article will help you get started training your own AI agents. Let’s start by understanding more about reinforcement learning.
Reinforcement learning is a machine learning technique to train AI “agents” to do tasks. It’s been used to create AI for a variety of games: from abstract games like Go to video games like Total War. Google’s AlphaGo was trained with reinforcement learning and beat the world champion of Go in 2016. Agents have also been created to play StarCraft II and Total War. Sounds impressive! But how does it work?
Throughout our lives, we’re often incentivized to behave in a certain way through rewards or punishment. For example, I give my cat a treat when he jumps through a hoop (what a good boy!). Reinforcement learning takes the same approach with tasks or games. It’s a technique used to find optimal behaviour through experience. Through many simulations, the agent makes choices and sees what reward or penalty they get. Over millions of plays, they understand what choices lead to the highest rewards!
In our situation, we want our agent to play Camel Up many times. On their turn they’re given the current board state: the position of the camels, what betting tiles are available, etc. They’re then asked to take an action. They can choose between the possible legal actions based on the board state. At first, the agent will just choose randomly and receives a reward based on its action. We then set it free to play LOTS of games, take actions randomly, and see how many points it gets.
To get technical for a moment, we’re going to use a certain type of reinforcement learning called Q-learning. This means that our agent keeps a lookup table, called a Q-table, where they lookup the current game state. The table contains the expected reward from each action based on prior experience. Each time it experiences a game, it will update this table with how it turned out. It learns over time! I guess that’s why they call it machine learning?
The reward that we’re giving the agent is their score. As it’s a points-based game, I thought that most natural. There’s also a bonus / penalty for winning / losing respectively. This is just one of many choices, and I’ll probably change this as this project evolves. The rewards can be more arbitrary, like extra rewards for taking betting tiles over rolling the dice.
This all sounds quite tricky, but never fear! Python is here! We’re going to make use of the gymnasium package maintained by the Farama Foundation. This package is a fork of OpenAI’s gym package and provides a useful framework for creating reinforcement learning agents. Let’s see how we apply this to our simulations.
To implement an agent we create a gymnasium environment. This runs a simulation of a game and asks the agent for an action when it’s their turn.
We define the environment in gym_env.py:
I needed to make some alterations to the core game code to make this work. The game needs to know when to pause for the agent to select an action. I added the “automated” attribute to the Player class so the game knew who to pause for. I also added the “run_stepped_turn” method to the Game object which simulates only until the next non-automated player turn.
The next part of our setup is to specify the agent. The agent needs to take in the current game state and return an action. We do this in the get_action method:
def get_action(self, obs: tuple[int, int, bool]) -> int:
"""
Returns the best action with probability (1 - epsilon)
otherwise a random action with probability epsilon to ensure exploration.
"""
# with probability epsilon return a random action to explore the environment
valid_action = False
while not valid_action:
if np.random.random() < self.epsilon:
proposed_action = env.action_space.sample()
# with probability (1 - epsilon) act greedily (exploit)
else:
proposed_action = int(np.argmax(self.q_values[obs]))
valid_action = env.unwrapped.action_mask[proposed_action]
logger.info(f"Taking action {env.unwrapped.action_mapping[proposed_action]}")
if hasattr(env.unwrapped.action_mapping[proposed_action], "color"):
logger.info(env.unwrapped.action_mapping[proposed_action].color)
return proposed_action
Reinforcement learning is a tug-of-war between exploring new options, and exploiting information already learned. The epsilon parameter controls the probability the agent chooses an action randomly (explores) or chooses what they think is the best option (exploit). We do need to make sure the action chosen is valid though. The agent can’t take a blue betting tile if there are none available!
We update the expected reward for each action based on the reward the agent receives for the action. This occurs in the update method where the Q-values (expected rewards) are adjusted:
def update(
self,
obs: tuple[int, int, bool],
action: int,
reward: float,
terminated: bool,
next_obs: tuple[int, int, bool],
):
"""Updates the Q-value of an action."""
future_q_value = (not terminated) * np.max(self.q_values[next_obs])
temporal_difference = (
reward + self.discount_factor * future_q_value - self.q_values[obs][action]
)
self.q_values[obs][action] = (
self.q_values[obs][action] + self.lr * temporal_difference
)
self.training_error.append(temporal_difference)
Results so far have been…disappointing. The agent so far underperforms even the basic die rolling strategy! I trained it on 500,000 games of Camel Up and the results are shown below.

Initially the rewards improve, but then start to drop off again. The win rate of the agent was also abysmal at just 5.46%. There are a few reasons I believe are to blame for this poor performance:
What are the takeaways? Well, I hope you have a better understanding of reinforcement learning and how we can apply it using the gymnasium library. I also hope that sharing my progress (and failures!) will help your own learning!
What’s next? I think spending some time focusing on the representation of the game state will be a fruitful exercise. I’ll lay that out in the next article, and we’ll see how much more compact we can make it!
Make sure you click subscribe to get notified when the next article drops!
Welcome back to another article in our series on winning Camel Up! If you’ve missed part 1, part 2, or our code review, you can find them here: How to Beat Your Dad at Camel Up / How to Beat Your Dad At Camel Up (Part 2) / How To Beat Your Dad At Camel Up (Interlude – Code Review)
Today we’re going to turn up the speed to 11! So far, our simulations have been completely CPU-bound. This means that while the code is simpler, simulations run slower. Simulating 100,000 games of camel up took approximately 10 minutes. This is partially because of the use of Python, and partially because of a lack of parallelism.
This has been fine for my purposes so far. However, I want a strategy with a savvy better who knows the odds of each camel winning the leg. They can then make an informed decision of the expected value of each betting tile. My expectation is that this would blow the “TakeLeader” betting strategy out of the water!
There’s a problem. It’s tricky to find the probabilities of each camel winning the leg given the game state. The only way I can see to do this is using Monte Carlo simulations. So, we want to run many simulations as quickly as possible!
What if I told you we can do better than our Python performance? What if I told you we can do BILLIONS of simulations in seconds? Well, we can using CUDA!
Simplistically, CUDA is the language of NVIDIA graphics cards. It underpins many popular machine learning libraries including PyTorch and TensorFlow. It’s very close to C/C++ in terms of syntax but requires a different approach to writing programs. It requires an understanding of memory and when to move data between the CPU & GPU. You can read more about CUDA here.
CUDA is really useful because graphics cards are great at parallel computation. For our purposes, this means that we can run simulated legs in parallel in separate threads. A 4060 has 24 streaming multiprocessors (SMs) which can each have over 1000 threads for over 24,000 threads running simultaneously! I thought this would be a really good approach for me to run my simulations. So, I set out to learn how.
Learning the basics of CUDA was a daunting affair. I’ll briefly sketch the path I took to writing my first programs. For reference, I am a fairly experienced Python developer that has not written much C++ before. So, I need to:
Familiarizing myself with C++
I hadn’t written much C++ before, so, brushing up my C++ was the first hurdle. I started by implementing basic data structures / algorithms using The Algorithm Design Manual. Writing implementations of linked lists and binary search trees introduced me to the syntax of C++. Once I felt more confident, I started solving Leetcode problems daily to practice the basics. After a couple of weeks I felt capable of starting to do more. I also started reading A Tour of C++ by Bjarne Stroustrup which was very useful in picking up C++ idioms.
Understanding how to write parallel programs
Parallel programs require a different thought process to other programs. Sasha Rush’s GPU-puzzles were super useful in learning how to think about CUDA programs. They’re based in Python and can be run on Google Colab. They step you through writing parallel programs from simple vector addition up to matrix multiplication. They also have cute pictures of puppies when you solve a problem.
Lecture material from the Oxford CUDA programming course were very useful in understanding more about CUDA directly.
Making CUDA run on my machine / graphics card
I needed to ensure my local development environment was correctly set up to use CUDA. Docker was extremely helpful here, in conjunction with the nvidia-container-toolkit. NVIDIA has a suite of CUDA-ready images which, while requiring some Docker knowledge, make the process seamless. I firmly believe that Docker is one of the most important tools for a software engineer to know. So, if you’re not familiar with it, now’s the time to start!
Now that we’re all set up, it’s time to write some CUDA! If you want to follow-along at home, the full code for this simulation can be found here.
The simulation aims to find the probability of each camel winning the leg given a game state. The important input variables are:
The simulation would then select a die to roll and move the appropriate camels until each die had been rolled. Then, it would record which camel won the leg, first by track position and tie-breaking by top of stack.
This loop appears to be fairly common in CUDA applications:
We need to start by making our input variables. We also allocate some space for the results on the CPU:
std::cout << "Creating host variables..." << std::endl;
int positions[NUM_CAMELS] = {0, 0, 0, 0, 0};
bool remainingDice[NUM_CAMELS] = {1, 1, 1, 1, 1};
int stack[NUM_CAMELS] = {1, 2, 3, 4, -1};
T *results;
results = (T *)malloc(NUM_CAMELS * sizeof(T));
I’ve made T a template variable depending on how many simulations you want to do. For a small number an int type will be fine. Once you start getting into the billionaire club, you’ll want something a little bigger! I’ve gone for an unsigned long long int to handle those huge numbers.
We also need to allocate memory for the results and the random seeds on the GPU. I used curand for random number generation on the GPU and it was relatively easy. The setup_kernel provides a different seed for each thread so that we do get different simulations.
std::cout << "Creating device pointers..." << std::endl;
T *d_results;
curandState *d_state;
cudaMalloc((void **)&d_state, BLOCKS * THREADS * sizeof(curandState));
std::cout << "Setting up curand states..." << std::endl;
setup_kernel<<<BLOCKS, THREADS>>>(d_state);
std::cout << "Allocating memory on device..." << std::endl;
cudaMalloc((void **)&d_results, NUM_CAMELS * sizeof(T));
cudaMemset(d_results, 0, NUM_CAMELS * sizeof(T));
I’ve chosen to copy across the input parameters into constant memory on the device. I initially had them as global memory passed into the kernel directly. This required every thread to access global memory many times. Using constant memory allowed cached read-only access by each thread to increase performance over using global memory. To do this, I declare constant variables at the top of the file and then copy using cudaMemcpyToSymbol instead of cudaMemcpy:
// Defines as constant memory in GPU kernel
__constant__ int d_positions[NUM_CAMELS];
__constant__ bool d_remaining_dice[NUM_CAMELS];
__constant__ int d_stack[NUM_CAMELS];
__constant__ int local_runs;
...
std::cout << "Copying to device..." << std::endl;
cudaMemcpyToSymbol(d_positions, positions, NUM_CAMELS * sizeof(int));
cudaMemcpyToSymbol(d_remaining_dice, remainingDice, NUM_CAMELS * sizeof(bool));
cudaMemcpyToSymbol(d_stack, stack, NUM_CAMELS * sizeof(int));
We’re now in a good place to actually run the simulation! the camel_up_sim kernel will run the simulations and store the results in the d_results array. We then need to copy that back across to the CPU, again using cudaMemcpy.
std::cout << "Starting sim..." << std::endl;
camel_up_sim<T><<<BLOCKS, THREADS>>>(d_state, d_results, RUNS_PER_THREAD);
cudaDeviceSynchronize();
std::cout << "Copying results back..." << std::endl;
cudaMemcpy(results, d_results, NUM_CAMELS * sizeof(T),
cudaMemcpyDeviceToHost);
std::cout << "Results are:" << std::endl;
printArray(results, NUM_CAMELS);
We then clean up after ourselves! No one likes a litterer…
cudaFree(d_positions);
cudaFree(d_results);
cudaFree(d_remaining_dice);
cudaFree(d_state);
cudaFree(d_stack);
free(results);
cudaFree specifically frees memory on the GPU, while free frees memory on the CPU.
Let’s now take a look at the kernel we’re using to simulate the leg. I’m not going to go through this line-by-line, but there’s a few bits I want to point out.
Aggregation of results
The final aggregation and reporting of results across threads is an important optimization of the code. The results variable is an array of length five, one slot for each camel. We need to get the results from all the threads to report back in an orderly way. My idea here is to:
I used __shfl_down_sync to sum the results for each thread in a warp. This will end with the first thread in the warp having the sum for all threads in the warp. That thread then reports to shared memory to aggregate across all the warps in the block.
for (int i = 0; i < NUM_CAMELS; i++) {
#pragma unroll
for (int offset = 16; offset > 0; offset /= 2) {
thread_results[i] +=
__shfl_down_sync(FULL_MASK, thread_results[i], offset);
}
// If it's the first thread in a warp - report the result to shared memory.
if (thread_idx % 32 == 0) {
atomicAdd(&shared_results[i], thread_results[i]); // explained below
}
}
The first thread in the block then takes the shared results and adds them to the final results array:
if (thread_idx == 0) {
#pragma unroll
for (int i = 0; i < NUM_CAMELS; i++) {
atomicAdd(&results[i], shared_results[i]); // explained below
}
}
The atomicAdd function has been used twice above. This reads the current value and writes back the sum in a transaction. This means we avoid race conditions between the different threads which would invalidate the results.
Local memory is actually global?
This is an area that I’m still learning about. Using local variables in the kernel can either be stored in registers, or global memory. If it gets stored in global memory then there is a significant performance overhead. Usually scalar variables are stored in registers, but arrays might not be. Arrays need to be both a size that the compiler can figure out at compilation, and also not referenced by a dynamic runtime constant.
int local_positions[NUM_CAMELS]; // Global?
bool local_dice[NUM_CAMELS]; // Global?
int local_stack[NUM_CAMELS]; // Global?
int dice_remaining; // registers
int eligible_camels[NUM_CAMELS]; // Global
int camel_to_move; // registers
int roll; // registers
int camel_on_top; //registers
int winner; //registers
What does this mean? I’m not 100% sure yet. I will need to consider alternate approaches to ensure our arrays are in registers or shared memory. This will be a topic of further research for me. Do you have any tips? Let me know!
I started by seeing how many simulations would complete in a short time. I used 100k simulations per thread, 1024 threads in a block, and 24 blocks in total. This led to 100000 * 1024 * 24 ~= 2.5b simulations which ran in approximately 4 seconds!
I then started profiling the code using the Nsight suite from Nvidia. I reduced the thread count as running the 2.5b simulations crashed Nsight! My code is still not optimal, but a few optimizations yielded a 31% speed-up.

#pragma unroll
for(int i = 0; i<NUM_CAMELS; i++) {
if(local_dice[i]) {
eligible_camels[j] = i;
j++;
}
}
camel_to_move = eligible_camels[curand(&local_state) % dice_remaining];
It’s clear that I need to improve my usage of the Nsight suite. I’ll be upskilling in this area using any courses & videos I can find, along with my own experimentation.
The next article will be about my experience creating a reinforcement learning player for Camel Up using gymnasium! Stay tuned!
Welcome back! This is a small technical interlude in our series on Camel Up. If you’re not up to date, you can find parts 1 & 2 here: How to Beat Your Dad at Camel Up / How to Beat Your Dad At Camel Up (Part 2).
Camel Up is a board game about betting on camels racing around a track in Egypt. I’ve spent the last couple of articles showing you some pretty graphs about the game. We also saw that you can dominate family games night by sitting on the left of your dad! Today I want to give an overview of the code generating those glamorous graphs! If you want to follow along, the GitHub repository can be found here.
I’m most familiar with Python so it was a natural choice for this project. I wanted development to be fairly quick and best practice. My overall aim was to have a small project that showed off use of tests on my public GitHub. I’ve made extensive use of testing in my professional career, but public proof of this was somewhat lacking. I also believe that the complexity of development is greatly reduced with tests, even without 100% code coverage. With tests, I have confidence that I’m considering edge cases, my code is working, and I can refactor without fear.
I’ve also used type-hints throughout the codebase as I believe these enhance the readability of the code. I think it also encourages simplicity as complex code makes pyright sad, and writing the right type hints becomes tricky. It’s often easier to simplify the code than get the right type hint.
Ease of development and clarity of code were prioritized over runtime speed. The performance is not terrible, however, simulating ~100,000 games takes approximately 10 minutes on my desktop PC. I re-visited this simulation while learning CUDA. Writing it in C++ with GPU acceleration shot performance to the moon! I simulated 2.5 billion legs of Camel Up within 4 seconds, which is far too much Camel Up for one lifetime!
In the rest of this article I want to take you through the main components of the code. We’ll look at the objects defined in camel_up/game.py starting from the most low-level and see how these combine together to simulate the game.

We’ll first look at the class representing the dice for the camels running in the race:
class Dice:
color: str
possible_values: list[int] = [1, 2, 3]
def __init__(self, color: str) -> None:
self.color = color
def __str__(self) -> str:
return f"Dice: {self.color}"
def __repr__(self):
return self.__str__()
def roll(self) -> int:
return random.sample(self.possible_values, k=1)[0]
When rolling we simply sample from the set of possible values. These values are hard-coded into the Dice class. With the modularity of the code, there is no reason that we couldn’t change this in the future. For instance, if we wanted to ask questions like “What would change if Camel Up had a 4-sided die?”
This dice has the ‘color’ attribute which links it to a specific camel. We also link to the Dice object from the Camel object. An alternative is to make the link in both directions, but this complicates initialization. Therefore, I made one side of the relationship have a ‘color’ string that can be used for matching.
class Camel:
dice: Dice
color: str
def __init__(self, color: str) -> None:
self.color = color
self.dice = Dice(color)
def roll_dice(self) -> int:
return self.dice.roll()
The Camel class automates the creation of our Dice object in the constructor. It also allows a public API to get a dice roll for that specific camel. I also like that if you squint and turn your head, the code kind of looks like a camel too!
We’re on a roll with our Dice objects – but we need somewhere to store them! It’s time to look at the Pyramid class which controls the rolling in the game. The Pyramid needs to store the Dice objects and whether or not they have been rolled this leg. A die is randomly selected when a roll action is taken from those that have not been rolled this leg. The selected die is rolled, and then recorded as having been rolled this leg.
class Pyramid:
dice: list[Dice]
dice_already_rolled: list[Dice]
dice_still_to_roll: list[Dice]
def __init__(self, dice: list[Dice]) -> None:
self.dice = dice
self.reset()
def roll_dice(self) -> tuple[str, int]:
dice_to_roll = self.dice_still_to_roll.pop()
self.dice_already_rolled.append(dice_to_roll)
return (dice_to_roll.color, dice_to_roll.roll())
def reset(self) -> None:
self.dice_still_to_roll = copy.copy(self.dice)
self.dice_already_rolled = []
random.shuffle(self.dice_still_to_roll)
The randomness in the pyramid is introduced in the reset() method. This method shuffles the list of dice when they are reloaded into the pyramid. This means that we just need to pop the top die from the list when a roll action is taken.
The last fundamental piece of the game we’ll consider are the betting tiles. These are related to a particular camel and have a payoff if that camel wins the leg. This payoff is either 2, 3, or 5 coins depending on the tile. All tiles pay 1 coin for second place and lose 1 coin for finishes outside the top two.
@dataclass
class BettingSlip:
color: str
winnings_if_true: int
I’ve chosen a dataclass here to simplify the implementation as it will automatically create the __init__ method for me.
We’ll now see how these building blocks come together elegantly to create something more complex. The GameContext class keeps track of the current board state. This is used to store things like the position of the camels, and the availability of betting slips. Below is a cut-down representation of its public API. There is a mix of helper functions to carry out actions like rolling dice, moving camels, taking betting slips. There are also query functions about the game state like “Is the leg over?”, or “Is the game over?”.
class GameContext:
camels: list[Camel]
betting_slips: dict[str, list[BettingSlip]]
track: dict[int, list[str]]
current_space: dict[str, int]
finishing_space: int
action_number: int
_pyramid: Pyramid
def take_action(self, player_action: Action, player: Player, **kwargs) -> None:
...
def is_leg_finished(self) -> bool:
...
def is_game_finished(self) -> bool:
...
def roll_dice_and_move_camel(self):
...
def get_leg_winner(self) -> str:
...
def get_leg_runner_up(self) -> str:
...
def get_top_betting_slip(self, color: str) -> BettingSlip:
...
def reset_for_next_leg(self) -> None:
...
def get_current_occupied_spaces(self) -> list[int]:
...
The ‘track’ dictionary has a key for each space on the board. Its values are lists representing the stack of camels on that space. The ‘current_space’ attribute is mainly a helper to speed up finding the correct camel on the track. This can be removed if we’re happy to search the track dictionary each time we want to move a camel. I think this is a helpful addition to the code to simplify some algorithms.
Now that we’ve created objects for the fundamental objects of the game, let’s consider the humans! We bring together the objects seen so far in the Player class. This is an important class that’s responsible for:
The player strategy has been abstracted into a PlayerStrategy object to make it more modular. The PlayerStrategy object is assigned to a particular Player. It takes in the current game state (the GameContext) and returns an Action for the player to carry out. This is a normal application of the Strategy design pattern.
As we’ve seen in the previous articles, the currently implemented strategies are the AlwaysRollStrategy and the TakeLeaderBetSlipStrategy:
class AlwaysRollStrategy(PlayerStrategy):
"""This strategy will always roll the dice, no matter what
the game context.
This is intended to be a baseline strategy that other
strategies can be compared to.
"""
def choose_action(self, context: GameContext) -> Action:
logger.info("Player is rolling dice...")
return RollDiceAction()
class TakeLeaderBetSlipStrategy(PlayerStrategy):
"""This strategy will take the current leader's top bet tile if possible.
Otherwise will roll the dice.
This is intended to be a baseline strategy that other
strategies can be compared to.
"""
def choose_action(self, context: GameContext) -> Action:
current_leader = context.get_leg_winner()
if len(context.betting_slips[current_leader]) > 0:
logger.info(
f"Taking betting slip of current leader which is {current_leader}"
)
return TakeBettingSlipAction(current_leader)
logger.info("rolling dice...")
return RollDiceAction()
When asked to choose an action, the Player class delegates this to its PlayerStrategy. This ensures modularity so we can easily create new strategies and switch out player strategies for simulations at will.
class Player:
strategy: PlayerStrategy
coins: int
betting_slips: list[BettingSlip]
automated: bool
player_number: int
def __init__(
self, strategy: PlayerStrategy, player_number=1, automated: bool = True
) -> None:
self.coins = 3
self.strategy = strategy
self.betting_slips = []
self.automated = automated
self.player_number = player_number
def gain_coins(self, coins_to_gain: int) -> None:
self.coins += coins_to_gain
def lose_coins(self, coins_to_lose: int) -> None:
self.coins = max(0, self.coins - coins_to_lose)
def choose_action(self, context: GameContext) -> Action:
return self.strategy.choose_action(context)
def take_betting_slip(self, betting_slip: BettingSlip) -> None:
self.betting_slips.append(betting_slip)
def return_all_betting_slips(self) -> list[BettingSlip]:
betting_slips = [a for a in self.betting_slips]
self.betting_slips = []
return betting_slips
def reset(self) -> None:
self.coins = 3
self.betting_slips = []
The Player class is also where the rule that a player cannot go into negative coins is enforced. The lose_coins method will have a hard-stop at zero coins. If only it worked this way in real life!
Let’s round out the article by talking about the current CI pipeline. Right now there’s no “deployment” for this code, so I just run the tests in the cloud. This ensures I’m not accidentally introducing regressions into the code. I will add in type-checking into the pipeline soon.
This repository has been created to show off some best practices like use of testing, CI/CD, and type hints. It has the side-effect of also being quite useful for finding out more about Camel Up! We’ve gone through the structure of the objects in the repository and the trade-offs made during development. I’ve also provided some tantalizing sneak-peeks of some upcoming articles where I used CUDA to simulated billions of legs! Let’s finish this article by seeing what else is coming up!
I’ve been working down a few different paths to expand this repository:
PRs are always welcome if you want to help out! Otherwise stay tuned for the next article in the series!
This is part 2 in a series about learning the deeper mysteries of Camel Up to prove my dad wrong. If you haven’t read it yet, you can find part 1 here.
Welcome back! I hope you’ve been applying our takeaways from the last deep dive! Today we’re going to turn up the heat and hopefully prove my dad’s favourite strategy wrong. Is rolling the dice a suckers move?
Just cos I’m a good guy, I’ll throw in the answer to another question as well: If you have a resident dice roller on game night, where should you sit to maximize your chances of winning?
To explore this we’re going to take a few different combinations of players with different automated strategies and compare their win rates. From this, we’ll learn how to maximize your chances of winning!
Each combination of strategies below was simulated 100,000 times to generate the win rates and figures. No, I didn’t lock myself in a room to play 100,000 rounds of Camel Up (I bet that’s a novel way to avoid cleaning the kitty litter). I coded up some simulations to get the computer to do the heavy lifting. If you want to see the code for this article, you can find that here.
Remember, the model we’re using is a cut-down version of the rules without boost tiles, end-of-game betting, and crazy camels. See Part 1 for more details.
As a refresher, three straightforward strategies have been implemented:
Now that we’ve laid out our strategies, let’s put them head-to-head and see who comes out on top.
Imagine it: three dice-happy players against one methodical bettor who waits for the perfect moment to snatch that leader’s tile. Who’s winning the camel race now? (Spoiler: It’s not the dice-rollers).

The player taking the betting tiles ran away with the win 90.7% of the time. I guess the dice-rolling crowd just didn’t have luck on their side that other 9.3%.
What about if you’re the only one not taking tiles? Just constantly rolling the dice? I simulated a game with three methodical players with the TakeLeader betting strategy and one aimless dice roller. How do you think it’ll go?

As you can see, absolutely terribly. These are rookie numbers!
This is unsurprising. The betting tiles have enough upside that usually a player is going to get lucky and get those sweet, sweet coins. Sure, the dice-roller gets a coin here and there, but when the chips are down (or, in this case, the camels), those coins seldom buy you a win.
Now that we know that getting those betting tiles has some serious upside, what should you do if you have a resident dice roller at your table? Can you take advantage of this poor, simple soul?
Here’s a claim that is settled law in our household, but see what you think.
Claim: The player to the left of the dice roller is advantaged most.
Why does this make sense? Well, the simple fact is that when a die gets rolled the information about the game updates. This can drastically change the chances of who wins a leg. The person on the left has the first opportunity to act on the new information. They can crunch the numbers and snatch up the highest-return betting tiles before anyone else gets a chance.
Below I’ve graphed the win rate of each player by their position at the table. Player 2 is our dice roller, and the other three players have the TakeLeader strategy.

Player 3, the player to the left of the dice roller, wins over half the time! You can see that their bar is over double the height of the next player.
What can we take away from all of this for our family games night?
Takeaway 1: Got a dice-happy friend at the table? Park yourself on their left like it’s prime real estate.
You’ll get the first chance to act on the new board state, which gives you a HUGE advantage. Even if you can’t be on their left, just don’t be on their right.
Takeaway 2: Even the simplest betting strategy is better than rolling the dice all day.
Our betting strategy is not particular complicated, just bet on the leader at that point in time. However, from the chart above you can see that everyone following this strategy does better than the dice roller!
What’s next in the series? We’ll dive into the nitty-gritty of the Python code that brought these simulations to life. Plus, I’ll show you how to harness the power of a graphics card to make those simulations zoom. If you’ve ever dreamed of coding up a true AI agent to take down the table, you won’t want to miss our upcoming exploration into reinforcement learning. Buckle up; it’s going to be a wild ride.
Don’t miss out on the next article, subscribe now to get notified when it drops.
“I like that he’s having fun. I just need him to know how wrong he is.”
Mr GrumpyKitten
My dad loves Camel Up. Seriously, this is a game that has brought him countless hours of joy. Despite our expensive game collection, it’s the one that he always requests. For most Millennials obsessed with games – this is a great situation. Your parents are willingly sitting down to the table to play with you? Mission Accomplished!
The problem is that I hate the way he plays. He constantly picks up that surprisingly satisfying plastic pyramid and rolls the dice. He even does this when we casually observe out-loud that Blue is certainly going to win the leg and there’s a Blue-3 betting tile just sitting there. He just wants to know what happens next! Don’t get me wrong – I like that he’s having fun. I just need him to know how wrong he is.
In this series, we’ll dive deep into Camel Up using mathematics & Python. You’ll learn enough along the way to thrash your family at your next games night! Who said mathematics was useless?
And so, a project was born: armed with my trusty degree in Math and seven years as a software engineer I sat down to prove how misguided he is. So, I reached for my favourite serpentine hammer and started building.
I modeled the game using Python, creating an environment where the game can be simulated using players with some straightforward strategies. You can check out the code on my GitHub here.
Right now, I’ve implemented a simplified version of the rules. For the time-being we won’t worry about the boost tiles, end of game betting, or the crazy camels from the second edition. I’ll add these in later. For now, this is sufficient to start asking (and answering) some questions about the fundamental structure of the game. (Need a refresher on the rules? Take a look here).
Right now, on an player’s turn, they can either:
Using these, I’ve devised two simple strategies for my horde of simpleton automated monkeys to carry out:
With the above, we can start to ask questions about the game at a fundamental level.
The first one: how many legs does the game usually last?
Let’s start with the theoretical minimum and maximum number of legs. Believe it or not, it is supremely unlikely but perfectly possible for the game to end on leg one! The maximum length is a whopping 16 turns. Personally – this sounds worse than a game of Settlers of Catan, but only just.
Skeptical? I don’t blame you but I swear I have evidence to back it up! If you’re feeling in a problem-solving mood, try to prove this yourself! Otherwise, I’ve included the full argument as a treat at the end of the post.
I’m going to throw out some claims so I can look like a genius when the data proves me right:
Claim 1 – The number of legs in the game is independent of the number of players
Claim 2 – The average number of legs should be less than 15 / 2 = 7.5 legs
Claim 3 – The distribution of the number of legs should be independent of player strategies
I simulated a whopping 100,000 games at each player count from 2-5 players (400,000 games total). Then, I made a pretty graph which you can see below. If you want to see how this is done you can follow along here.

Let’s compare the results with the claims.
Claim 1 – The number of legs in the game is independent of the number of players
The chart shows that the distribution is consistent as the bars are the same height regardless of the player count. This validates claim 1. Good job GrumpyKitten.
Claim 2 – The average number of legs should be less than 15 / 2 = 7.5 legs
The average number of legs is 4.72 which is less than 7.5 as expected. Including the free roll during set-up, this implies that the winning camel travels (17 – 2) / 4.72 = 3.17 spaces per turn on average. This is only possible if the camel is a beneficiary of some stacking!
Claim 3 – The distribution of the number of legs should be independent of player strategies
To try to argue this claim I repeated the simulation above with all agents having a different strategy. This yielded yet another pretty graph! I gave the agents the TakeLeaderBettingSlip strategy instead of the AlwaysRollDice strategy. What we see is that the distributions are almost identical between the two strategies.
This, along with the theoretical argument above, provides us with some proof that the player strategies do not alter the number of legs in the game.

We’ve learned some lessons about the underlying structure of a game of Camel Up. We learned about how many legs a game will last (4-5 on average). We’ve also explored some ideas about how player strategies don’t affect the number of legs. Unless. of course, you’re manipulating things with your boost tiles!
So what does this mean for your family game night? With our new understanding of the game’s dynamics you can plan your moves more strategically – especially when it comes to timing your end-of-game betting cards. Over 90% of the time the game will end at either 4, 5, or 6 legs. If you’re on leg 4 – you should really think about end-of-game betting . With a high player count the game can end before you have enough turns to make your bets.
When you win your next game, you’re welcome. Ready for more? Let’s see where this is going next!
The next post in this series will tackle two questions:
We’ll continue to add to our model and answer interesting questions as we go further through the project. We’ll also look later in the series at how to train a reinforcement learning algorithm using gymnasium to play Camel Up!
Believe it or not, it is possible (but supremely unlikely) for a camel to cross the finish line on leg 1.
Consider a scenario where:
The total distance that the camel on top of the stack will move is a staggering 5 * 3 = 15 spaces! Including the 3 from set-up yields 18 spaces – enough to win the game!
In another unlikely scenario, it can take 16 legs for a camel to cross the finish line.
Imagine:
Then each camel moves exactly 1 space during the leg. Repeating this and remembering the 1 space from setup gives 16 legs for our camels to labour to the finish line.
Calculating the probabilities of the above occurring is left as an exercise to the reader. I will note that the charts above have no games that ended on leg 1.
I was lucky enough to go to PyCon US 2024, held in Pittsburgh, Pennsylvania from May 17-19. A long trip from my usual home in Melbourne, Australia!
I flew from Melbourne to Pittsburgh via San Francisco on United Airlines. I had a very long stopover in San Francisco, about 14 hours, so I left the airport and went into the city! I arrived around 8am, set up my Cutter card, and ventured out on the BART to the Embarcadero. It wasn’t my first time in San Francisco, having spent three months there as a twelve year old, but it was nice to see with adult eyes. I bought a ticket for the hop-on hop-off bus and spent the day exploring. Highlights were walking through Golden Gate Park and watching the EPL at a bar. I also saw a dog that had some John Lennon glasses – he was a real cool cat.


After San Francisco I took a red-eye flight to Pittsburgh, I was pretty exhausted by this point. I managed to get a bit of sleep on the plane but it had been about 40 hours of minimal sleep by that point. I checked in at my hotel and got some breakfast and went straight to PyCon!
These were in the main hall and consisted of keynote speakers. These were interesting and informative, and an important part of the experience. The lightning talks also took place in the plenary hall, these were short talks that anyone could sign up to give, and you got to hear a lot about the awesome things that others are doing with Python! Highlights for me were the robotics demonstration by deshipu and learning to count using binary by Anthony Shaw.
I’m sure that you’re familiar with PyCon talks, and being in the room was a very similar experience to watching them on YouTube. I found it more difficult to meet people in these sessions as there was enough space that everyone spread out and didn’t sit near each other. The highlight for me was the talk on Hatch. However, after attending these for one day, and knowing that they’d be available on YouTube eventually, I ended up prioritizing Open Spaces.
Open spaces were the highlight of my PyCon experience! Each day there were many free rooms that were able to be booked by attendees to discuss whatever topic they’d like. These sessions were free-form, interactive, and non-recorded. I attended some great discussions, including a session on Cyber Security run by the OWASP foundation, a discussion on Python in Excel, a general Data Science meetup, and discussions about what made a Python application “production ready”. I also felt like I got to network more in these sessions than in the talks.

Large parts of PyCon only exist because of volunteers, and it’s great to give back to the community. Examples of things you can do is to volunteer on the information booth, at the check-in counter, or to be a facilitator at a talk. I volunteered on the check-in desk for a few hours on my first day, it was an awesome way to meet people (and combat my jet lag!). The process is simple, signing up via the PyCon app, and people extremely helpful and friendly!
These occurred after the main conference, and were an opportunity to contribute to an open-source project. I initially worked on a Rust-based project, and my Rust skills were not up to the challenge! I then pivoted to work on BeeWare and ended up having two pull requests merged. They even gave me this cute challenge coin!

Breakfast, lunch, and coffee were provided by the conference and these meals were incredible! The organizing committee did an incredible job sourcing catering. It was also a great way to meet people, most tables were half-full, so you could sit anywhere and strike up a chat.
I quite enjoyed Pittsburgh while I was there. I spent a lot of time downtown, but it really shined when I ventured further afield.
Some highlights:


I also went to see the mighty Pittsburgh Riverhounds play in their scenic riverside stadium. The stadium experience was great, I had a burger from the concession stand and enjoyed a great evening of soccer!

This was an amazing experience that I would definitely do again. I learned a lot at PyCon and was made aware of packages I wasn’t aware of, and the open spaces allowed me to learn directly from others. I’d highly recommend this to anyone considering to go!