Introduction to AI


Introduction to AI

Michael
Welcome everyone to CS50's lecture on Artificial Intelligence! We're especially excited to have family members joining us today. For our students, let's give a big round of applause to all the family members who came to support you. It's truly wonderful to see so many of you here.

Anna
That's fantastic! And as our CS50 students know, a common programming practice involves having a rubber duck on your desk. We even provided one a few weeks back. The idea is to verbalize your coding problems or confusion to it.

Michael
Exactly. The thought is that by explaining your problem out loud, even to an inanimate object, you often gain clarity and solve it yourself. It's that 'aha!' moment. We've actually virtualized this rubber duck in CS50's Visual Studio Code environment.

Anna
Initially, our virtual duck was a simple chat window that would respond with just a few quacks. Believe it or not, we have anecdotal evidence that even those quacks were enough because the act of typing out the problem helped students figure things out.

Michael
Right, the process itself was the solution. But, of course, with the advent of tools like ChatGPT, Claude, and Gemini, our duck evolved. In 2023, it started responding in English, becoming a less helpful version of ChatGPT, designed to guide rather than just give answers.

Anna
That's a clever approach, mimicking a good teacher. Today, we're diving into the underlying building blocks of this generative AI, the technology that allows us to create images, sounds, video, and text. It's fascinating how quickly this field is progressing.

Michael
To kick things off, we're going to play a game to test how good we humans are at distinguishing AI from reality. If you have your phone, scan the QR code on screen. CS50's preceptor, Kelly, will help us run the poll.

Anna
We'll be using some examples from The New York Times, which published both AI and non-AI generated content. It'll be interesting to see how sophisticated this technology has become. Let's see if we can spot the AI.

Michael
Alright, everyone, on your phones, you should see two photographs. The question is, which one of these is AI? Is it the left or the right image? Feel free to raise your hand if you're not seeing the prompt. Responses are coming in!

Anna
It looks like over 70% of you think it's the one on the right. And you know what? You're absolutely correct! The image on the right was indeed AI-generated. Perhaps it looked a little too perfect or slightly unreal, that's often a tell.

Michael
Let's try another example. Same QR code, no need to re-scan. Here are two more photographs. Again, which of these is AI? Left or right? Take a moment to consider your choice. The responses are a bit closer this time.

Anna
A majority of you are leaning towards the left, though 5% are honestly admitting they're unsure. Kelly, if you can swipe back to the photos, the answer this time was actually a trick question! They were both AI.

Michael
That's right, both were AI! Neither of these faces exists in the real world; they were synthesized from massive amounts of training data. It really shows how incredibly good this technology has gotten at creating realistic images.

Anna
It's truly impressive and a little unsettling. Now, let's switch to text, which is what our duck focuses on. The question is: Did a fourth grader write this, or a new chatbot? Here are two short essays.

Michael
Essay 1: 'I'd like to bring a yummy sandwich and a cold juice box for lunch. Sometimes I'll even pack a tasty piece of fruit or a bag of crunchy chips. As we eat, we chat and laugh and catch up on each other's day.' And Essay 2: 'My mother packs me a sandwich, a drink, fruit, and a treat. When I get into a lunchroom, I find an empty table and sit there and eat my lunch. My friends come and sit down with me.' Which one is AI?

Anna
The poll results are duking it out, but a majority are saying Essay 1. Michael, why do you think people chose that one? What are the telltale signs here? I'm curious about the audience's reasoning.

Michael
Yes, someone suggested that Essay 2 sounds more like what a real child would write. And indeed, the answer is that Essay 1 is the AI. Essay 2 is more akin to what a fourth or fifth grader would write. The vocabulary in Essay 1, like 'catch up on each other's day,' seems a bit advanced for that age.

Anna
That's a great point. This game, while fun, is becoming increasingly difficult to play. Our goal today is to help you understand not just how tools like our duck work, but the foundational principles of AI that have been developing for decades.

Michael
These principles have really come to fruition recently, thanks to advances in research, more powerful cloud computing, and the sheer volume of data available to train these technologies. The duck itself is built on a complex architecture.

Anna
It uses APIs from companies like Microsoft and OpenAI, which have developed the core models. We then add our own CS50-specific 'sauce' to tailor the duck's responses. A key part of this is something called prompt engineering.

Michael
Ah, prompt engineering, a term popping up everywhere! It's less about traditional engineering and more about asking good, detailed questions and providing context to the AI to get the desired answer. There are two important terms to know.

Anna
Right, a 'system prompt' and a 'user prompt.' The system prompt consists of instructions written by us, often in English, to give the AI a specific personality or domain of expertise. For example, our duck's system prompt sets its persona.

Michael
Exactly. Our system prompt essentially says, 'You are a friendly and supportive teaching assistant for CS50. You are also a rubber duck.' This simple instruction is enough to give the AI its character. It also specifies that it should only answer CS50 computer science questions and avoid giving full answers to problem sets.

Anna
So, after that preamble, the 'user prompt' is just the student's actual question. This setup ensures the duck behaves like a helpful tutor, not just a random chatbot, aligning with our pedagogical goals. It's a precise way to guide the AI's behavior.

Michael
Precisely. And CS50 students might recall from week zero, when we first introduced the course, we demonstrated some code using OpenAI's library. Now, with some Python under their belts, that code should make more sense.

Anna
We imported the OpenAI library, created a client variable, and defined a user prompt from user input. We also set a system prompt that day, I think, to limit the answer to one sentence and pretend to be a cat. It was a fun example.

Michael
Yes, we then used `client.chat.completions.create` to pass in the user prompt, system prompt, and the specific AI model, then printed the response. We saw it work, but didn't delve into the 'how' or 'what more' we could do with it.

Anna
Today, we're peeling back another layer, something students can't use until their final projects: AI-powered code generation. Here in VS Code, I'm opening a past assignment, a spell checker in C, which took students many hours to implement.

Michael
Right, students had to fill in four functions in `dictionary.c`, a task that typically took 5 to 15 hours. Now, I'm going to show you how AI can drastically speed up this process, not by just changing languages, but by using these powerful tools.

Anna
On the right side of VS Code, you've enabled Copilot, a feature similar to products from Google and Anthropic, but this one is from Microsoft and GitHub. It offers a chat window and other features to assist with coding.

Michael
Exactly. I'll just type 'implement the check function using a hash table in C' and hit enter. Copilot uses the open file, `dictionary.c`, as context. It's also familiar with CS50 itself, having been trained on our open courseware for years.

Anna
It's essentially looking for patterns in its vast training data to solve the problem you've described. It's not 'thinking,' but it's incredibly effective at finding relevant solutions. And look, on the left, highlighted in green, is the suggested code!

Michael
It might not be identical to how a student would implement it, but it certainly contains the essence of a hash table implementation. I can choose to keep all this code. Now, let's try the 'load function'.

Anna
So, you just ask it to 'implement the load function,' and it leverages comments in the code, implicit input/output information, and its training data. It has enough context to fill in those blanks, just like a good TA or engineer.

Michael
Indeed. And as you can see, the suggested code for the load function appears in green. I've spent far fewer minutes talking about this than CS50 students spent coding it from scratch. I'll click 'keep,' but that's a big assumption about correctness.

Anna
That's the crucial point. While AI can generate code quickly, a programmer still needs to understand it to troubleshoot, explain, or modify it. The 'muscle memory' and vocabulary developed through manual coding are still essential.

Michael
Absolutely. But once you have that foundational understanding, AI like Copilot amplifies your capabilities overnight. It handles the tedious parts, freeing you to focus on high-level problem-solving with other humans, which is incredibly exciting.

Anna
It allows for much grander projects to be tackled in a shorter timeframe. Let's try another example: problem set one, Mario. You can describe the problem in plain English and see if the AI can implement it.

Michael
I'll create an empty `Mario.c` file and type: 'Please implement a program in C that prints a left-aligned pyramid of bricks using hash symbols for bricks and use the CS50 library to ask the user for a non-negative height as an integer.' This is essentially the entire problem description.

Anna
And it's already working, using the file name as a hint and leveraging its vast training data. It's providing an English explanation, and CS50 students will recognize the core structure: a do-while loop for input, and then loops to print the pyramid.

Michael
Boom, it's done! These are bite-sized problems. For your final project, which is much more open-ended, this amplification of your abilities will allow you to implement far greater projects than previously possible in just a few weeks.

Anna
That's a powerful promise. So, how does any of this actually work? We started with generative AI, creating images and text. But what is AI fundamentally, and what are its underlying building blocks that led us to these capabilities?

Michael
Consider spam detection. We take it for granted that Gmail or Outlook filters most spam. No human is manually labeling every incoming message. Code, and increasingly AI, figures out what looks like spam and routes it correctly, usually 99% of the time.

Anna
Or handwriting recognition. Microsoft and Google don't know everyone's handwriting style, but they've been trained on enough samples to recognize patterns. Odds are, your handwriting is similar enough to someone else's for them to convert it to digital text.

Michael
Streaming services like Netflix are another great example. They're excellent at recommending 'if you watched X, you might also like Y.' This isn't a massive 'if-else' statement for every movie; it's dynamically figuring out what you and I might like based on our viewing habits and others'.

Anna
And voice assistants like Siri, Alexa, and Google Assistant. They don't have every possible question pre-programmed. They dynamically generate responses. But let's rewind a bit to earlier forms of AI, like the classic game Pong.

Michael
Pong, one of the first arcade games, involves two paddles and a ball. Players move their paddles up and down to hit the ball. Playing against the 'CPU' or 'AI' was a core part of the experience, even if it wasn't as sophisticated then.

Anna
A successor, Breakout, is similar. One paddle, one ball, bounce it off colored bricks. We humans instinctively know where to move the paddle. If the ball goes left, we move left to catch it on the way down.

Michael
We can quantify that instinct algorithmically using decision trees. This is a concept from economics, strategic thinking, and computer science. For Breakout, we could ask: 'Is the ball to the left of the paddle?' If yes, move left.

Anna
If no, you don't just blindly move right. You'd then ask, 'Is the ball to the right of the paddle?' If yes, move right. Otherwise, stay put. This deterministic approach perfectly maps to code using simple if-else statements.

Michael
Indeed. A `while` loop, with `if`, `else if`, and `else` statements, can perfectly implement a computer player for Pong or Breakout. It's straightforward coding for optimal play in these simpler games.

Anna
Now, consider Tic-Tac-Toe. Two O's and two X's on a board. The goal is three in a row: vertically, horizontally, or diagonally. How would a computer solve this? You first ask, 'Can I get three in a row this turn?'

Michael
If yes, you play that square and win. If not, you ask, 'Can my opponent get three in a row on their next turn?' If so, you block them. Tic-Tac-Toe is relatively simple, but not always obvious. We humans often use heuristics, like favoring the middle.

Anna
Exactly. But are those heuristics optimal? If you've ever lost a game of Tic-Tac-Toe, you're not playing optimally. At worst, you should force a tie; at best, you should win. The question of 'what's the best move?' isn't always immediately clear.

Michael
One algorithm for optimal play is MiniMax, which involves minimizing or maximizing scores. We'll assign scores: O wins is -1, X wins is +1, and a tie is 0. X wants to maximize its score, O wants to minimize.

Anna
So, on this board, X has three in a row, so its value is 1. Now, let's look at a simpler board where it's O's turn, with two possible moves. If O goes top-left, X will win, resulting in a score of 1. If O goes bottom-middle, X will go top-left, leading to a tie, score 0.

Michael
O wants to minimize its score, so 0 is better than 1. O will choose bottom-middle, forcing a tie. This logic ensures optimal play. If you lose Tic-Tac-Toe, it means you didn't follow this optimal logic, even if you could.

Anna
The challenge is that the decision tree for Tic-Tac-Toe grows rapidly. With more moves left, it becomes exponentially larger, making it impossible for a human to calculate all possibilities in their head. We rely on instinct.

Michael
A computer, however, can calculate all 255,168 possible ways to play Tic-Tac-Toe. It can determine the optimal move for X by choosing the highest score, and for O by choosing the lowest. This makes it a perfectly solvable game for a computer.

Anna
But what about more complex games, like chess? Even considering just the first four moves, there are 85 billion different ways to play. And for the game of Go, it's an astounding 266 quintillion possibilities for the first four moves!

Michael
This is where traditional if-else logic and brute-force calculation fail, even for powerful computers. We just don't have enough memory or processing power. This is where AI truly shines, solving problems indirectly.

Anna
Instead of explicitly coding every rule, you train the computer to figure out how to win by showing it promising board configurations and configurations to avoid. This is what we call machine learning: machines learning to solve problems from massive datasets.

Michael
Reinforcement learning is a type of machine learning that we humans use all the time. Let's look at a fun demonstration: teaching a robot to flip pancakes. A researcher shows the robot how to do it a few times.

Anna
The robot has an arm that can move in X, Y, and Z coordinates. Initially, it won't do very well. But with reinforcement learning, the human rewards the robot for good flips and 'punishes' it for mistakes, like dropping the pancake.

Michael
It's like giving a digital cookie for success and a proverbial slap on the wrist for failure. Parents often use this, whether consciously or not, to train children. Over time, the robot's movements, the X, Y, Z coordinates, get refined.

Anna
After about 50 trials, the robot gets remarkably good at flipping pancakes. It's learned through trial and error, reinforced by rewards and punishments. This applies to games too, like exploring a map.

Michael
Imagine a game with a yellow player dot, a green exit, and lava pits. We can see the optimal path, but the player only moves up, down, left, right. If it goes into lava, it's 'punished' with a lost life or points, learning not to repeat that move.

Anna
As it explores, it eventually finds the exit and is rewarded. Now it can follow that successful path repeatedly, like us playing Super Mario Brothers decades later. But is this the *best* way to play?

Michael
My 7th-grade assistant points out that I've moved many more times than necessary. The robot just exploited its current knowledge, not necessarily finding the shortest or most optimal path. We need to explore a bit.

Anna
This is the principle of 'exploring versus exploiting.' We tend to exploit what we know works, like ordering the same favorite dish at a restaurant. But if we sprinkle in some randomness, we might discover something even better.

Michael
Yes, with an 'epsilon' variable, say 10% of the time, the computer makes a random move instead of the known 'best' move. This doesn't guarantee a win immediately but, over many trials, it allows the AI to find a more optimal path, becoming a better player overall.

Anna
We can see this in an AI playing Breakout. Initially, it moves randomly, but after hundreds of episodes, it learns that hitting the ball increases its score and missing decreases it. It starts getting pretty good.

Michael
Then, it gets a little creepy. If you let it play long enough, it discovers a 'trick': by breaking through the top row, it can let the ball bounce around and clear the rest of the bricks without further interaction, maximizing its score. It figured that out on its own.

Anna
That's a powerful example of reinforcement learning in action. Beyond that, we also have supervised learning, which we've been using for years, like our initial spam example. Humans label data, like marking an email as spam, which trains the algorithm.

Michael
However, manually labeling millions or billions of data points doesn't scale. It's expensive and unrealistic. This leads us to unsupervised models and deep learning, where humans aren't in the loop in the same way.

Anna
Deep learning, inspired by biological neural networks, is the state-of-the-art underlying today's rubber duck and large language models like ChatGPT. A neuron transmits a signal, and multiple neurons intercommunicate, like from thought to action.

Michael
As computer scientists, we abstract neurons as circles and connections as lines, forming a graph. Two input neurons might lead to one output, representing problem-solving. Let's consider a simple 2D world with blue and red dots.

Anna
If we only have two dots, we might draw a vertical line to separate blue on the left and red on the right. With a third dot, we adjust the line. With enough dots, we can create a 'best fit' line to predict the color of new dots based on their X and Y coordinates.

Michael
This simple neural network is trying to find three parameters: A, B, and C, for a formula like AX + BY + C. If the value is greater than zero, it predicts blue; otherwise, red. With enough data, it refines these parameters.

Anna
In reality, neural networks have billions of neurons and connections, each representing a mathematical value learned from training data. We might know the inputs and outputs, but the internal workings, the 'why' of each weight, are opaque due to the sheer volume of data.

Michael
If you want to predict rainfall from humidity and pressure, those are your inputs leading to one output. Or advertising spend predicting sales. It's all about training on massive volumes of data to establish these complex relationships.

Anna
Bringing it full circle to CS50's rubber duck and large language models like ChatGPT: these are generative pre-trained transformers, essentially neural networks trained on vast amounts of textual information, enabling interactive chat.

Michael
An example: completing the sentence, 'The state's capital is...' Historically, this was hard because 'Massachusetts' and 'capital' were far apart in the text. Also, pronouns like 'state' refer to 'Massachusetts,' which confused early AIs.

Anna
Now, we break sentences into words, each represented by a vector of numbers, like 1,536 floating-point values for 'Massachusetts.' Then, 'attention' is calculated, showing relationships between words.

Michael
Thicker lines in the attention model imply stronger relationships, like between 'Massachusetts' and 'state.' When you feed the sentence, 'The state's capital is,' to the neural network, it's statistically predicting the most probable next word.

Anna
Based on all the Reddit posts, Google results, and encyclopedias it's trained on, the answer will hopefully be 'Boston.' But sometimes, as you know, it makes mistakes, which we call hallucinations.

Michael
Yes, hallucinations occur when the AI just makes something up, perhaps due to faulty training data or that 1% 'exploration' leading it astray. Even CS50's duck is fallible, despite our efforts to minimize errors.

Anna
It's a poetic reminder of the limitations, even of advanced AI. Michael, that reminds me of Shel Silverstein's poem, 'The Homework Machine,' which years ago, in a way, predicted our current state with AI. Can you share a bit of that?

Michael
Absolutely, it's a perfect ending. Shel Silverstein wrote: 'The Homework Machine, oh the Homework Machine, most perfect contraption that's ever been seen. Just put in your homework, then drop in a dime, snap on the switch, and in 10 seconds' time, your homework comes out quick and clean as can be. Here it is, 9 + 4, and the answer is 33?'

Anna
Oh me, I guess it's not as perfect as I thought it would be! A wonderfully insightful poem that still rings true today. What a great way to think about the advancements and ongoing challenges in AI. Thank you for this fascinating discussion, Michael.

Michael
My pleasure, Anna. And thank you all for joining us for this lecture on AI. This was CS50. See you next time!

Ask anything
We've read this whole study set, so questions about it get the best answers.