cosas interesantes
Para que no se olviden:
생각想法pensamientosthoughts/theories
God of the Gaps
- Gaps in scientific knowledge is proof of God’s existence
Fermi Paradox
- Absence of extraterrestrial life in spite of the high estimated probabilities of their existence
- Zoo Hypothesis
- We live in metaphorical zoo in which extraterrestrials are observers but we can’t observe them
“What-The-Hell” Effect
- Making one bad decision and leading to more
- What the hell, may as well eat another one… and so on
Zipf’s Law
- Frequency of a word in any language is inversely proportional to its rank
Pareto Principle
- “The Law of the Vital Few”
- 80% of consequences come from 20% of causes
- 80/20 rule
Infinite Monkey Theorem
- A monkey hitting keys on keyboard at random for infinite amount of time will produce every possible finite text an infinite amount of times
100 Prisoners Riddle
- 100 prisoners have to go in a room one by one and select the box that contains a slip with their number in it
- Select the box number with their number on it
- Creates a “loop” that must loop back to original number (their number)
- 31% chance of winning
Trolley Problem
- Practical (benefit for majority)
- Save 5 by choosing to switch lever
- Moral (according to a set of ethical rules)
- Don’t switch lever
The Chinese Room
- Man stuck in room receives note in Chinese one day
- Desperate to communicate, and uses provided books to provide responses
- Doesn’t actually know what the notes or his responses mean
- Argues that computer-executing program doesn’t have a mind no matter how human-like the computer may behave
- What is intelligence?
Mary’s Room
- Mary stuck in a colorless room since birth
- Has read only books on color perception, knows everything there is to it
- If the door is open and she sees the outside world of color, will she learn anything new?
- Does understanding necessitate conscious experience?
Brain in a Vat
- We’re disembodied brains whose mental perceptions are caused by supercomputer
- Computer is simulating reality
- Skepticism
- Argues that can’t prove one isn’t a brain in a vat → can’t prove that one’s beliefs are even true
Friendship Paradox
- Our friends are statistically more likely to have more friends than us
Black Swan Theory
- A single event “black swan event” or observation that comes as a surprise, difficult to predict in the normal course of business
- Changes our entire outlook on something
- Ludic Fallacy
- Misuse of games to model real-life situations
Allais Paradox
- Undermines theory of expected utility

- 1A: 1m, 1B: 1.39m; 2A: 110k, 2B: 500k
- People will choose 1A and 2B, even though they are opposites
- Expected utility expects people to either choose 1A and 2A, or 1B and 2B
Mandela Effect
- Large # of people believe an event occurred when it did not
Semantic Satiation
- Repetition causes word/phrase to lose meaning → repeated meaningless sounds
The Linguistics Iceberg Explained
- Plural of octopus is octopuses (Greek root)
- Other words like fungus, cactus → fungi, cacti (Latin root)
- Pangram - sentence that has every letter in alphabet
- Gendered languages influence how people think of innate objects?
- E.g. la luna → study shows more likely to be described with feminine portrayal
Dangers of population growth facilitation
- Fewer children → senior-centered nation → more short-term thinking, wealth > innovation
- Bad for issues such as climate change, which needs innovation
Fundamental question of rationality - “Why do you believe what you believe?”
Reciprocity Bias
- Natural tendency to return favor when they receive something from others
- More likely to receive unsolicited gift after giving unconditional gift
Suspension of disbelief
- Avoidance of critical thinking and logic in order to believe it for the sake of enjoying the narrative
- E.g. ignoring plot holes, one piece plot armor cheese
Lateral thinking
- Problem-solving in unique and creative ways rather than step-by-step approach
- Look at problem from different angle
The Cobra Effect
- Situation where intended solution makes problem worse
- E.g. bounty for each cobra killed in colonial India → started breeding cobras
Heisenberg Effect
- Directly observing event alters it
Dunning-Kruger Effect
- When someone overestimates knowledge or abilities in particular area

Straw man fallacy
- Someone distorts opponent’s argument by oversimplifying/exaggerating
- Misrepresents opponent’s argument to make it easier to attack
Sapir-Worf hypothesis
- Language person speaks influences how they think about the world
- E.g. gendered language in professions “policeman” “fireman”
Unexpected hanging paradox
- Prisoner told he’ll be executed at noon during a random weekday upcoming week, which will be a surprise
- Reasons that can’t be Friday b/c if not executed on Thursday then Friday isn’t surprise
- Uses recursive logic to conclude that he won’t be executed on any of the days
- Executed on Wednesday, to his surprise
- Logic seemingly defeats itself (reality contradicts perfect logical reasoning)
Fallacy fallacy
- Claim that argument is wrong solely because it contains logical fallacy
Pro-drop language
- Pronouns can be omitted when they can be pragmatically or grammatically inferred
- English is non pro-drop
- E.g. Mandarin is pro-drop
A) 这块蛋糕很好吃。 谁烤的?
B) 不知道。喜欢吗?(I) don’t know. (you) like (it)?
Escher Sentence
- Sentence that initially seems acceptable but upon further reflection have no well-formed meaning
- More people have been to Berlin than I have
Pandas suck at existing
- Bamboo very little nutritional value and substance → spend 12 hrs a day eating
- Digestion tract resembles carnivore (shorter) instead of herbivore → poop 40 times a day
- Look clumsy because they look for lowest-energy way to get around
- Young bamboo shoots and culm/leaves have lots of protein → targeted feeding → 61% protein energy from diet
- Reflected in panda milk, higher protein proportion than herbivorous mammals
The Savanna Hypothesis (Pliocene)
- Drying-cooling (less humid/rainfall + global temperature drop) opened up forests creating savanna landscape
- Resources became patchily distributed across space
- Resources within specific forest patches would quickly become scarce (resource competition)
- Some individuals may have been better able to walk upright than others (phenotypic variation)
- Bipedal locomotion is most efficient to travel long distances (+ other benefits e.g. spotting predators) → travel to new patches at lower costs and mortality rates
- These individuals would be more likely to survive and reproduce, passing this trait on to their descendants (differential survivorship)
Lack of Terrestrial Bioluminescence
- 0.1% of terrestrial/air animals are bioluminescent, compared to 75% of marine animals
- No clear explanation
- Theories:
- Darkness? (polar vs terrestrial darkness)
- 3D domain (water) compared to 2D on land
- Land obstacles may obstruct light anyways
Poe’s Law
- Adage of internet culture that says without a clear indicator of author’s intent, any parodic or sarcastic expression of extreme views can be mistaken by some readers for being sincere
Big-Headed Ants’ Rippling Effect
- Human globalization → big-headed ants become invasive species in Africa, probably from one of the islands in Indian ocean → endanger lives of acacia ants who protect acacia trees → acacia trees lose protection → decrease in acacia tree population by elephants + other predators → less cover for lions to attack zebras → more zebras survive, water buffalo targeted more
Portmanteau
- Word blending sounds and meanings of two other words
- E.g. “Hinglish”, “bromance”, “spork”, “podcast” (ipod + broadcast)
Newcomb’s Paradox
- Near-perfect predictor (Omega) offers two boxes: one box with transparent $1k, other mystery box
- You can either take only mystery box, or both boxes
- Omega made a prediction about your choice before you even entered the room with near-perfect accuracy
- If it predicted you would take both boxes, mystery box would have $0
- If it predicted you would only take mystery box, mystery box would have $1m
- Taking only mystery box (expected utility) vs taking both (strategic dominance)
- Strategic dominance: one strategy yields better outcome regardless of opponent’s actions
- E.g. always defecting in prisoner’s dilemma
Chinese dialects
- Shanghainese is left-prominent: underlying tone of the first syllable of multisyllabic word dictates the tone of each of the following syllables (less stressed/prominent)
- Part of Wu Chinese language group (mostly in eastern China)
- Wenzhounese nicknamed the “Devil’s language” 鬼语
- Middle Chinese used to have final pulmonic consonants (-p, -t, -k)
- Some dialects still retain this (e.g. Gan Chinese and Cantonese (yue yu) )

책书librosbooks
“죽고 싶지만 떡볶이는 먹고 싶어”
- People can be more attached to people who’ve “chosen” them as their friend even if the affection isn’t truly returned (‘they’ve chosen me, they can’t possibly betray me’)
- If you find meaning when spending time together, does the nature of the relationship matter?
- Living to have good social perception is like eating junk food that eventually rots your teeth
“Blink” by Malcolm Gladwell
- Ability to find patterns based on very short experiences (seconds)
- Snap judgments
- Warren Harding errors
- Unconscious assumptions that can be fueled to drive conscious decisions without our awareness
- E.g. tall, dark-complexioned, handsome man (Warren Harding) → unconscious expectation that he’s competent to be president
- Some radical concepts/designs are seen as “ugly” (proxy for “different” in such cases) until it takes enough time for us to like them
- Facial expression codes (FACS) give cues to emotion
- Mind reading (read faces to interpret situation - lack of is autism)
- Mind blindness caused by arousal (HR above 145) and lack of time
- We are often careless with rapid cognition
- Acknowledge subtle influences that can alter bias in our unconscious
- We can control environment in which rapid cognition occurs
- E.g. controlling spontaneity of first impressions
- Forgive people trapped in circumstances where good judgment is imperiled
- Information is often not understanding
- Visual is 80% of audition, when removed → better music
- Lee knowing more about Hooker’s army in Chancellorsville and still lost
- Deliberate analysis (pro’s and con’s) when considering minor importances
- Instinct for more complicated nature
“The Man Who Mistook His Wife for a Hat and other Clinical Tales” by Oliver Sacks
- Only distinguish people by their unique features, if they have any
- Korsakoff's Syndrome
- Proprioception - body’s ability to locate itself in orientation, balance
- Lack of → cannot feel or sense her physical self
- Haldol rebalances dopamine
- Reduces symptoms of schizophrenia, tourette syndrome
“The Confidence Game” by Maria Konnikova
- People like extraordinary circumstances, magic, and stories which confidence game feeds on
- Confidence games thrive during periods of transition
- E.g. industrial, technological revolution
- Con artist and victim (grifter and the mark)
- Dark triad personality theory
- Psychopathy (emotionless), narcissism (selfish), Machiavellianism (deception)
- Identifying victim (put-up)
- Familiarize with victim to gain trust → open more information
- Creation of empathy and rapport (the play)
- Emotion before logic
- Stories are more persuasive and immersing than facts
- Mood congruity
- Elaboration Likelihood Model
- More involved → central route - persuaded by content
- Less involved → peripheral route - persuaded by external cues (e.g. appearance)
- Relief following anxiety is most vulnerable state of being persuaded
- Logic and persuasion (the rope)
- Alpha (increase appeal) and Omega (decrease resistance)
- Foot-in-the-door, door-in-the-face
- Disrupt-then-reframe (DTR) technique
- Change situation every time victim tries to assess message to disrupt understanding
- Decision fatigue (excessive options) → irrational thinking
- Illusory truth effect
- More likely to perceive as true if familiar with it
- Cognitive overload
- Cons take advantage of people’s illusory superiority, that we are singular (special) no matter the circumstances
- “Too good to be true” → “Actually, this makes perfect sense”
- Lake Wobegon effect
- Human tendency to overestimate themselves
- Most people are average
- Enhanced recall of interrupted events
- If perform poorly, memory dismissed from mind → vulnerable to cons
- Evaluate how it will benefit (the convincer)
- The more we struggle, less we can extricate ourselves (the breakdown)
- Victim may even increase involvement (the send)
- Completely fleeced (the touch)
- Con artist may not even need to tell us to be quiet (the blow-off and fix)
“The Tipping Point” by Malcolm Gladwell
- Three types of people in marketing
- Connectors - know a lot of people, friendly, sociable
- Mavens - knowledgeable, curious
- Salesmen - pitch idea well, persuasive
- Rule of 150 - humans can comfortably maintain network of 150 people
- Metcalfe’s Law “fax effect”
- Value of telecommunication network is proportional to how many users there are
- Also introduces immunity, e.g. emails → creates cluster
- Crime is largely caused by environment rather than intrinsic factors e.g. graffiti
- Most people get information from very small subset of people who seek risk
- These people cause tipping point (widespread popularity)
“Sapiens: A Brief History of Humankind” by Yuval Noah Harari
- Humans survive because of ability to create fiction
- Exchange between other humans
- Dual reality
- Stones, rocks, trees, sun
- God, religion, video games
“Homo Deus” by Yuval Noah Harari
- Knowledge-based economy instead of materials → war profitability decreases
- Chekhov’s Law - if a gun was introduced in first frame, it would/should be used inevitably
- Agricultural Revolution → theistic religions, justify domesticating animals
- Does the mind exist?
- If subjective feelings are the result of electrochemicals in our brain, then where is the mind
- Turing test - machine vs human, distinguish which is which
- Human superiority is due to their flexible cooperation in large numbers
- E.g. bees can’t form republics in response to danger, elephants can’t cooperate within lots of strangers
- Religion: Ethical judgment + factual judgment = practical guideline
- Humans obey God + God deemed homosexuality bad = people avoid homosexual activities
- Modern culture = economic growth (capitalism)
- Humanism
- Follow individual feelings rather than divine inputs
- E.g. war art more focused on individual perspective, rather than overall layout
- Liberal humanism
- Individual free will
- Customer is always right, “if it feels good, do it”
- Some argue that not the best because struggles to account for ideological contradictions among humans
- Account for others’ feelings and socio-economic system
- Party knows best, trade union is always right
- Darwin’s evolutionary theory
- Human experiences collide → strongest survive
- War is essential
- Freedom of information
- Organisms are algorithms–what will happen to society when algorithms know us better than ourselves?
- Which is more valuable: intelligence or consciousness?
“The Three-Body Problem” by Cixin Liu
- Dyson sphere
- Cosmic velocities
- 1st cosmic velocity: speed to bring object in orbit around Earth
- 2nd cosmic velocity: escape velocity from Earth
- 3rd cosmic velocity: escape solar gravitational field
- 4th cosmic velocity: escape Milky Way galaxy gravitation
- If life has transformed Earth so much, then what effect has life had on the universe up to this point → is universe/life even natural?
- Time is 2D
- Dark Forest Theory - solution to Fermi Paradox
- Based on 2 axioms of cosmic sociology
- Civilizations’ goal is to survive
- Civilizations grow and expand, but total matter in universe remains constant
- Even if one civilization says it’s peaceful, other civilizations won’t know if they’re lying → safest to eliminate them
- Chains of suspicion (best to kill) and threat of technological explosion (best to maintain peace)
- Everyone remains in hiding, if civilization encounters another, then only option is to kill them
- Nature of fundamental laws of physics
- Archer shoots holes in 2D world 10cm apart, creatures on that world think that there exists a hole in the universe every 10cm (law of physics)
- Turkey notices farmer feeds them at certain time every day (law of physics), so he tells other turkeys this on day of Thanksgiving, where farmer kills them all
“Algospeak” by Adam Aleksic
- Scunthorpe problem: unintentional blocking of online content by spam filter bc text contains unacceptable substring
- Bowdlerization: removing/altering content considered inappropriate
- Grawlixes: string of typographical symbols used in place of obscenity, especially in comic strips
- Minced oaths: type of euphemism, polite or softened substitute for swear word
- “Pen” and “pencil” are not linguistically related
- “Pencil” comes from latin word “penis” meaning “tail”
- “Pen” comes from Latin word “penna” meaning feather
- Euphemism treadmill: word or phrase intended to be more polite substitute for an offensive term, eventually acquires same negative connotation → repeat
- E.g. “idiot” → “retarded” → “mentally disabled” (retarded used to be polite substitute for idiot)
- Leetspeak: standard letters replaced by numerals or special characters that resemble letters visually (different from algospeak)
- Transition from language associated with lower classes (18th c.) to “informal speech”
- “O.K” originated from giving “all correct” an American slang fad to give incorrect abbreviations → Boston print media helped it reach mainstream usage
- 2023 Oxford study found that creators are purposefully minimizing their creativity to pander to perceived algorithmic tastes and enhance visibility
- “Engagement treadmill”: algorithm pushes word as a trend → creators use word → more people interact with word → reinforces algorithm again
- Phrasal template: familiar, repeatable phrases where any word can be inserted
- E.g. “on __” (God, my mother, skibidi, etc.)
- Helps words survive by allowing them to be used in more contexts
- Reddit source code used to be open-source, now closed source since 2017 → creators abused algorithm that determines how likely post will appear on feed (dependent on two variables: difference between upvotes - downvotes, and post age)
- Curiosity gap: gap between what you know and what you want to know (marketing technique)
- Using group dynamic language e.g. “you”, “people”, “only one” to connect with viewer
- “Am I the only one who didn’t know X?” as openers
- Attention economy: attention as limited resource to be allocated among competing stimuli in information-rich environment
- Algorithm keeps track of retention rate: how long people watch videos before scrolling to next one
- “Trendbaiting”: confidently saying some term so people would think it’s a term they missed out on → popularizes term toward being a trend (e.g. “boomer ellipses”)
- “No because” is a discourse marker
- Matthew Effect: small advantages → exponential wealth accumulation, vice versa
- Each additional attention-grabbing strategy contributes exponentially to success
- Nothing inherent that makes dialect sound better than another, just our prejudices
- E.g. British associated with wealth and power → British accent sounds “better” than Indian
- “Influencer accent”—uptalk (declarative sentences end with rising pitch)
- Affectation: forcing another accent or manner of speech
- Linguistic founder effect:
- Beastification: popularization of MrBeast video format with high-budget, fast-paced, attention-grabbing content to maximize viewer retention
- Filter bubble (filter out information and prioritize content you’ll be interested in based off past activity) → echo chamber (environment that reinforces existing views)
- Context collapse: content/linguistic norms of one group spreads into other communities
- Speeds up euphemism treadmill bc out-group misuses terms in inappropriate contexts, speeding up pejorative connotation
- 2022 study shows politicians engaging in greater online incivility because civility produces less engagement
- Goodhart’s law: as soon as metric becomes target, it ceases to be a good metric
- Stated vs revealed preferences
- Stated: content that we would consciously choose to be interested in
- Revealed: content aligned to unconscious, automatic, emotional reactions
- Thought-terminating clichés: loaded expressions that cut off any dissonant thinking
- E.g. “cope” or “it’s over” → stops any further introspection
- Radicalized language, extreme views, insular echo chamber → language creation → influence mainstream more through engagement treadmill and Matthew effect
- Offensive words remained in-group
- Online disinhibition effect: anonymity makes it easier to spread negativity
- Poe’s law: any sarcastic expression of extreme views can be mistaken for sincere expression of those views
- “Cool” had previously only been used in AAE
- West African concept of itutu (aesthetic of beauty/calmness associated with cold temperature)
- Adopted by mainstream → linguistic appropriation
- Digital blackface: using black reactions as exaggerated response (e.g. crying MJ) to perpetuate racial stereotypes
- AAE constantly scrutinized and sought after at the same time
- SEO (search engine optimization): including kinds of phrases that people look up to → developers nudge algorithms into directing traffic toward their websites
- Platforms create microlabels (e.g. “pastel goth” or “coastal cowgirl”) and thus in-group communities → new demographic that can be advertised to
- Long-tail model: business strategy where companies make profit by selling lots of unique products to niche markets rather than same few products to popular markets

- Originally started in catalogs of upscale retailers → began being sold ini youth-targeted fast fashion stores e.g. Hollister
- Marketed “preppy” to upper-middle-class girls → preppy began to refer to bright, stereotypically girly clothing, transitioning away from “upper-class style of American ‘preparatory schools’”
- Enshittification (Cory Doctorow)
- Social media platforms make experience as good as possible for users to build up following
- Once users are locked in, platforms will make experience was good as possible for businesses trying to advertise to the users
- Once users and business are locked in, platforms will exploit them to make money
- Optimal distinctiveness: balance our need to belong with our need to be distinct
- Gravitate toward groups and identities in the middle ground
- Flanderization: exaggerating certain personality quirks to maintain interest and optimize engagement → can make character feel shallower
- Engagement treadmill can lead to subculture flanderization by taking advantage of their once-unique words
- How algorithms filter content has changed social learning
- Acquire new behavior through algorithms that bring us most extreme content
- Irony of increasing # of queer community labels, which has traditionally been about rejecting labels
- “Low-key devoró”, “desvivir”
- Real Academic Espanola and Academie Francaise tasked with translating word → used calques rather than loanwords → unlike English, such slang was given direct institutional backing → language involved in more standard, centralized direction
- Replacement of geographic dialects to digital one (e.g. K-pop dialect, Swiftie dialect)
- ASL adapting to structure of social media
- E.g. “dog”’s original gesture would appear off-screen → social media users change it so that it fits screen
- People create more one-hand gestures (other hand to record)
- Deaf creators have disadvantage online bc silence → people scroll past
HARRY POTTER 해리 포터
“Harry Potter y la piedra filosofal”
- Hagrid move Philosopher’s Stone from Gringotts to Hogwarts
- Quirell (face couldn’t be seen) gave Hagrid Norbert to find out how to get past Fluffy (lullaby music)
- Snape was trying to stop Quirell from stealing stone during troll incident (leg injury)
- Snape trying to save Harry from Quirrell during Quidditch
- Hermione set robe on fire, broke Quirell’s attention too
- Sorcerer’s stone defenses: Fluffy, Devil’s Snare, chess, flying keys, potion riddle
- Mirror of Erised - shows deepest desires
- Quirell couldn’t touch Harry b/c he was connected to Voldemort → Lily’s love protection
- Stone appears in Harry’s pocket after looking at Mirror of Erised
- Nicolas Flamel creator of Philosopher’s stone, died after he and DD destroyed it
“Harry Potter y la cámara secreta”
- Dobby blocked 9¾ entrance, enchanted bludger, cut off mail from friends
- Gilderoy Lockhart - autograph dude
- Dragged into chamber entrance by Ron & Harry → hit by his own memory-loss spell using Ron’s wand → permanently clueless
- Made Harry’s bones disappear in an effort to cure broken bone from Q
- Malfoy conjured snake to attack Harry → Harry spoke in parseltongue to save it from attacking Justin Finch-Fletchley
- Voldemort parseltongue to Harry when he tried to kill him
- Tom Ryddle opened Chamber, framed Hagrid for it and got him expelled (reasonable since Hagrid liked dangerous creatures - Aragog)
- Ginny becomes too emotionally attached to diary Horcrux → possessed by its soul
- Harry saved by Sorting Hat (Sword of Gryffindor - only summoned by a true Gryffindor) and Fawkes (loyal to Dumbledore)
- Stabs diary with Basilisk fang (contains basilisk venom → kills Horcrux)
- Harry frees Dobby by hiding sock inside diary which he gave to Lucius
“Harry Potter y el prisionero de Azkaban”
- F&G give Harry Marauder’s Map
- Ron give Harry Pocket Sneakoscope as birthday gift
- Lights up when enemies are around
- Keeps lighting up at dinner table (Scabbers is Peter Pettigrew?)
- Remus Lupin werewolf - anti-werewolf potions brewed up by Snape
- Knight Bus - Stanley Shunpike
- Saved Harry from the Grim (Sirius?)
- Buckbeak execution (Macnair) saved by Hermione’s Time Turner
- Sirius escape
- Recognized Pettigrew as rat on Ron’s shoulder in newspaper during trip to Egypt
- Turned into dog and escaped
- Sirius Black was secret guardian of Potter family, gave it to Peter Pettigrew last second because he thought Voldemort wouldn’t expect it
- Pettigrew betrayed Potters by telling Voldemort where they were
- Pettigrew framed Black by cutting off finger and claiming that he had killed everyone
- Trelawney predicted in her rant that Voldemort would rise to power with the help of a follower (night that Pettigrew escaped)
- Sirius gives Harry permission to go to Hogsmeade → DD allows, other teachers won’t question
“Harry Potter y el cáliz de fuego”
- Hermione vs Percy abt Crouch’s treatment toward Winky (Percy is Crouch simp)
- S.P.E.W organization founded by Hermione with 3 total members
- “Mad-Eye” Moody was auror (trained to catch bad wizards)
- Sent Karkarov to Azkaban, released by pleading he was regretful and singing
- Hagrid teaching classes, blast-ended skrewt
- Triwizard Tournament - created between Hogwarts, Beauxbatons (Madame Olympe Maxim), Durmstrang (Karkarov)
- 1st test: Hungarian Horntail - get the golden egg
- 2nd test: The Lake - retrieve person you value the most (Ron)
- Carried by Dobby (gillyweed) and Moaning Myrtle (directions)
- 3rd test: Labyrinth - Cup is in center
- Portkey to Voldemort’s father’s grave in Little Hangleton (made by Barty Crouch Jr.)
- Pettigrew target-killed Cedric instantly
- Bone of father, flesh of follower, flesh of enemy (wanted Harry to have protection that mother gave him) → Voldemort back to life
- V give Pettigrew silver hand as reward for his service
- Harry escaped during duel, used summoning charm while holding Cedric to retrieve Cup and return to Hogwarts
- Aftermath
- Voldemort can touch Harry b/c used Harry’s blood (Lily’s protection also to V)
- Harry’s & Voldemort’s wands came from Fawkes
- Victims come out of V’s wand b/c sister wands collide (invoke previous spells in inverse order)
- Karkarov ran away while Harry was fighting Voldemort
- Crouch’s son was fake Moody
- Mother wanted Crouch to free son as last wish (she was dying), Crouch agreed → used polyjuice potions, everyone thought Crouch’s son was dead
- Crouch used Imperius on son, permanently under invis cloak
- Bertha Jorkins came by one day, realized who Winky was talking to → Crouch put powerful memory-spell on her
- Resisted Imperius during World Cup, grabbed Harry’s wand and invoked Dark Mark
- Winky was not “saving seat for Crouch,” was occupying Crouch’s son seat (under invis cloak)
- Crouch dismissed Winky for not keeping son in check
- Voldemort came to his house one night, used Imperius on Crouch, free’d son
- Had been recovering slowly in forest with help from Pettigrew and torturing Bertha Jorkins for Triwizard Tournament information
- Crouch went to work as usual, when started to resist, forced to send letters from home stating that he was sick
- Task: make sure Harry gets to 3rd test and touches Cup
- He and Pettigrew attacked Moody, polyjuice on him, stored him nearby for polyjuice-material usage, Imperius to find out about habits (e.g. drink from own bottle)
- In-Tournament Genius Plays
- Didn’t want to appear too sus after helping Harry in 1st test
- Told Cedric how to open egg, knew that he would tell Harry too
- Gave Neville book on aquatic plants bc he thought Harry would ask him about it, but he didn’t
- Told Dobby to come to office to clean tunic while he talked with McGonagall about gillyweed (framed so that Dobby would tell Harry)
- Used Snape’s office for polyjuice materials (why Crouch was on map) → took map from Harry lying that Crouch hated Death Eaters just as much as himself (Moody)
- Used Map to find out Crouch was near Harry & Krum after labyrinth introduction → hid in invis cloak until Harry went off to find Dumbledore → killed Crouch, stunned Krum
- Looped back around when Dumbledore came to seem like he was coming from castle (lied that Snape had told him about this)
- Turned Crouch into a bone, cover with invis cape, buried next to Hagrid’s cabin
- Labyrinth: stunned Fleur, used Imperius on Krum to take out Diggory, cleared out most obstacles for Harry
- Fudge brought dementor to where Crouch Jr. was → dementor’s kiss
- F&G and Bagman incident
- F&G won bet at WC that Ireland would win but Krum would get snitch
- Bagman gave them leprechaun gold (disappeared soon), refused to give money
- Bagman needed money b/c owes goblins → made bet with them that Harry would win tournament → tried to help Harry
- Goblins claimed that Harry tied, so Bagman is broke and fled
- Harry gave F&G his prize money to start up joke shop business
- Hermione caught Rita Skeeter (undocumented animagus → beetle), no writing for a year
“Harry Potter y la Orden del Fénix”
- Figg is squib, orders from Dumbledore to keep watch over Harry, didn’t act nice to him so he wouldn’t suspect anything
- Dementors attack Dudley and Harry (Mundungus was lackin’ on his job - take turns guarding Harry)
- Order of Phoenix takes Harry to HQ (Grimmauld Place - Sirius’ parents’ old house); Kreacher crazy elf
- Fudge influence The Daily Prophet to portray Harry as stupid boy → less credibility → Voldemort isn’t back
- Percy promotion incident
- Mr. Weasley thinks Fudge is using Percy to spy on his family and Dumbledore
- Percy flames him: not ambitious → poor, ministry > family
- All pure-bloods are related (e.g. Tonks, Malfoys)
- Pro pure-blood, but not to extremes of Voldemort
- Sirius’ brother Regulus killed by Voldemort after becoming DE, too scared
- Sirius removed after running away from home at 16
- Lived in James Potter’s home and off gold uncle Alphard gave (also removed)
- Ministry entered through telephone booth → underground
- Enchanted windows (weather chosen every day), flying notes (used to be owls)
- Hearing
- Held in same place as Lestrange, Fudge Jr. sentencing
- Umbridge, Fudge, Percy vs Dumbledore, Harry, Figg
- Harry absolved
- Ron & Hermione, Malfoy & Pansy prefects (1b 1g per House)
- Luna Lovegood’s father is director of The Quibbler
- Fudge scared of Dumbledore raising secret army → passes random laws and gets Umbridge to supervise classes, teach no-magic DaDA class, MINISTRY CORRUPTION
- Hagrid gone (Grubbly-Plank)
- Umbridge punishment - “I must not tell lies” with pen that uses blood from dorsal
- Ron made Quidditch team - very nervous, sensitive to Slytherin insults “Weasley is Our King”
- Hermione knitting objects for elves, hiding them in secret places so they find them → elves don’t clean tower → Dobby takes everything
- Dumbledore’s Army
- Those interested met in Hog’s Head (Mundungus eavesdropped → Order of Phoenix knew - guarding Harry)
- Come & Go Room / Room of Requirement
- Appears when someone is in desperate need of smth
- Every member has Enchanted Coin with numbers, indicates if Harry changes date for practice time
- Cho & Harry kiss under mistletoe, cries about Cedric the whole time
- Harry can sense Voldemort’s emotions
- Umbridge suspends Harry + Fred + George from Quidditch for fighting Malfoy, gets replacements (Ginny is Seeker)
- Ginny practicing Quidditch by sneaking in garden since she was 6
- Traveled with Olympe Maxime to giants
- Followed orders from DD, give Karkus (Gurg - head of giants) gifts
- Karkus killed, Golgomath (next Gurg) not as friendly
- Tried to convince runaway giants in nearby caves, but Golgomath supporters hunted down all of them
- Macnair also there giving gifts
- Left with nothing but shred of hope that some might listen to Dumbledore
- Thesthrals - skeleton horses, only ppl who’ve seen death can see them (Harry, Luna, Neville)
- Harry’s vision: Arthur Weasley bitten by snake
- Harry saw it from snake’s perspective
- Not possessed (can’t appear/disappear within Hogwarts, would have long periods of memory loss - Ginny)
- Dumbledore use former directors’ portraits to check on Mr. W
- Portkey to get to Grimmauld’s Place
- San Mungo Hospital
- Lockhart still clueless
- Longbottoms, mother gives Neville lots of chewing gum wrappers which he keeps secretly
- Occlumency (mind defense ) training w/ Snape
- Occulumency defends against Legilimency (penetrate in mind)
- Voldemort realizes that Harry can experience his thoughts, will try to do same with Harry → occlumency training requested by Dumbledore
- Harry realizes 6-month dark hallway dream is in Department of Mysteries
- Where Arthur Weasley got attacked by Voldemort snake
- Where Voldemort’s weapon is
- 10 Death Eaters escape from Azkaban, Sirius is framed by Ministry
- Lucius Malfoy used imperius curse on Bode & Sturgis (guy in newspaper caught sneaking in Ministry) to rob weapon for Voldemort
- Firenze new Adivination teacher after Trelawney gets fired
- Umbridge vs DA incident
- Marietta Edgecombe (Cho’s friend) snitches to Umbridge abt DA
- Hermione’s enchantment on member list → Marietta can’t talk to provide witness evidence, grows pimples
- Kinglsey memory spell when ppl weren’t looking, witness is useless
- DD claims responsibility for DA → disappears from Hogwarts
- Umbridge replaces as new director
- Inquisitorial Squad - group of students (Malfoy, Parkinson, etc.) to support Umbridge/Ministry
- Snape’s worst memory
- Malfoy goes to office to ask Snape to rescue Montague (stuck in toilet) → Harry explores pensieve
- James bullying Snape, saved by dirty-blood Lily Evans
- No more Occlumency lessons, Harry feels conflicted/betrayed with father
- Individual career interview w/ McGonagall - willing to help Harry to become auror “if it’s the last thing [she does]”
- F&G escape
- Cause chaos → Harry talk w/ Sirius abt father “he got more mature w/ time”
- Started dating Lily in 7th year
- Umbridge catches them → fly out of Hogwarts, advertise business in epic fashion
- Harry finally confesses to R&H how F&G got money for business
- Grawp
- Hagrid drags H&H out during G vs. R game (Ron pops off cus “nothing to lose”)
- Introduces to Grawp - half brother, bullied for being “too small”
- Why Hagrid took so long to come back, bruises everywhere
- Made them promise to take care of Grawp if Hagrid gets fired
- Saw Hagrid get fired (McGonagall injured, taken to SM) during astronomy OWL at night
- When Sirius told Kreacher to leave during Christmas, Kreacher took it seriously → left to Narcisa (BL’s sister, Lucius wife)
- Told her about Harry & Sirius relationship, fed to V →
- Harry gets baited, V torturing Sirius
- Checks Umbridge’s fireplace to see if Sirius is at GP
- Kreacher had injured Buckbeak to make Sirius treat him so Kreacher capped that Sirius wasn’t there
- Caught by Umbridge, Hermione baits Umbridge with “weapon,” leads her to forest with centaurs, carried away
- H&H&R&Ginny&Neville&LL ride thestrals to Ministry
- Snape had already confirmed Sirius was in GP and safe, realized Harry was gonna go after him in Ministry, alerted rest of Order
- Ministry
- Rotating doors room, Hermione marks visited doors to counter
- Tank with brains room, weird murmuring arch room, bookshelves room
- V tried using Sturgis & Bode to rob it, discovered only ppl mentioned in prophecy can retrieve it → baited Harry to get it for him (V can’t j show up at ministry)
- Why V tried to kill Harry when he was just a baby
- Sirius killed by Bellatrix Lestrange (also killed Longbottoms)
- Fudge comes in PJ’s, admits Voldemort is back → DD forces him to kick Umbridge, allow Hagrid to come back
- DD sent card along w/ baby Harry to Dursleys, pact that made Petunia keep Harry in house
- As long as Harry called that place home, V couldn’t hurt him there
- DD interviewing Trelawney for Adivination position in Hog’s Head, heard prophecy
- The one with the power to vanquish the Dark Lord approaches... born to those who have thrice defied him, born as the seventh month dies... and the Dark Lord will mark him as his equal, but he will have power the Dark Lord knows not... and either must die at the hand of the other for neither can live while the other survives... the one with the power to vanquish the Dark Lord will be born as the seventh month dies....
- V will choose him, give him powers
- One will kill the other
- Snape overheard, kicked out, only heard 1st part → Voldemort choose Harry instead of Neville w/out knowing that it’d backfire
- “Biggest regret” of Snape’s life
- Harry coping abt Sirius death
- Sirius can’t return as ghost, Headless Nick doesn’t explain why
- Harry finds two-way mirror that Sirius gave him at beginning, say his name and they can communicate w/ each other
“Harry Potter y el misterio del príncipe”
- The other minister
- Muggle minister informed by Fudge abt V, wizarding world news
- Unexplainable things happening in muggle world
- Fudge dismissed as minister, replaced by Rufus Scrimgeour
- Shacklebolt working undercover for muggle ministry
- Draco’s mission - kill DD
- Narcisa begs Snape to an unbreakable vow that he’ll help Draco (now a DE) complete it
- Snape still untrusted by BL
- DD pick up Harry to go to The Burrow
- Harry inherit everything Sirius had, sent Kreacher to kitchen, Buckbeak “Witherwings” to Hagrid
- Adult age = 17 in wizarding world, protection of “home” will go away then
- V use occlumency against Harry, realize how dangerous having mind read could be
- Inferius (pl. inferi) = dead bodies reanimated by spells of DE (like zombie puppets)
- Horace Slughorn
- Had club/network of favorite students
- Move from house to house when muggles on vacation
- Accepted position at Hogwarts after Harry & DD convince him
- V’s return → ppl rushing into relationships “uncertainty of future,” clock hands pointing to “mortal peril”
- Bill & Fleur planning to get married, Mrs. W inviting Tonks over every night hoping that Bill will fall in love w/ her instead
- OWL results: Hermione 9 O’s, 1 E in DaDA; Harry & Ron both did well
- Karkarov assassinated for abandoning DE’s
- Draco gets Borgin to fix something for him
- Draco threatens Borgin with having Fenrir Greyback check on him, forces him to fix something (mission?) and buys smth
- Greyback - werewolf that hunts children & indoctrinates them to hate wizards, part of V’s army
- Bit Lupin when he was small
- Draco realizes Harry’s eavesdropping his compartment’s convo → stuns him & beats him up, leaves him under invis cloak
- Saved by Tonks, realized Harry hadn’t left (had cloak on) → checked closed-curtained compartment
- Slughorn Potions, Snape DaDA
- Grawp moved away to mountains that DD found
- Felix Felicis-making contest
- First class of Potions with Slughorn
- Harry didn’t anticipate taking potions → borrows used book from Half-Blood Prince which contains modifications to book’s recipe → Harry wins contest
- Gaunts last living descendants of Salazar Slytherin - instability rising due to tradition of marrying w/ cousins, fewer and fewer
- Solozar Gaunt (V’s grandfather) - father
- Ogden sent by ministry to condemn Morfin (son) for committing magic to defenseless muggle
- Morfin snitched to Solozar abt Merope (daughter) liking Tom (V’s father) → Solozar tried to strangle Merope for liking muggle → ministry reinforcements came and Morfin/Solozar sent to Azkaban
- Merope finally free from Solozar’s oppression → love potion on Tom and got married → stopped using love potion once pregantn, thought he’d stay with her anyways → Tom ditched
- Merope + V’s invitation to Hogwarts
- Merope desperate for gold → sold Slytherin’s opal necklace for mere 10 galleons (wasn’t aware of value) to Caractacus Burke (Borgin & Burkes)
- Died after delivering V to orphanage
- Dumbledore visits to invite V to Hogwarts
- V liked collecting things he stole from others, bad things happen to ppl who annoy him, never cried, no friends
- V frames Morfin for murders of Ryddle family
- Used memory spell
- Stole Marvolo Gaunt’s Ring (descendant of Slytherin)
- V asks Slughorn about horcruxes (Slughorn’s memory)
- V was prefect and part of Slug Club, admired by other students
- This was blurred borrowed memory from Slughorn → left out worst parts
- DD assigns Harry hw: make Slughorn reveal real memory
- Murder of Hepzibah Smith (Hokey’s memory)
- V was working at Borgin & Burkes, assigned job of convincing people to sell treasures
- Stole Hepzibah’s Hufflepuff’s Cup & Slytherin’s Locket, framed murder on Hokey (elf)
- V left B & B before family realized treasures disappeared
- DD denies V of DaDA position
- No professor since has had position for more than a year (cursed?)
- V wanted to come back to Hogwarts to train army? Look for valuable objects from Hogwarts founders to place Horcruxes in?
- Stanley Shunpike DE?
- Quidditch tryouts corruption
- Goalkeeper position: Hermione enchanted Cormac McLaggen’s last ball → missed, got robbed; made Ron’s balls easier to hit
- Katie Bell incident in Hogsmeade
- Delivering packet to someone (under imperius?)
- Went crazy when Leanne took it from her → Hagrid carried her to Hogwarts
- Opal necklace in packet (Slytherin one that Merope sold to Burkes)
- Same necklace Malfoy was looking at in Borgin & Burkes 4 years ago
- Harry & Ron caught Ginny & Dean making out → Ginny roasts Ron’s love life → Ron bad mood → Harry pretends to put felix felicis in pumpkin juice
- Ron pops off, learns that it was all him → makes out with Lavender Brown → Hermione mad now
- Hermione invites McLaggen to party to piss off Ron
- Harry invites LL spontaneously
- Overhears Draco + Snape talking, Draco unwilling to share w/ Snape abt plan
- Draco claims he had nothing to do with Katie Bell incident
- Scrimgeour & Percy pretends that they working near The Burrow, Percy wanted to see family (cap) → Scrimgeour tries to get Harry to become a mascot, symbol of hope for public, which he refuses to be
- Bezoar is antidote for mostly all potions
- Apparition classes taught by Ministry dude
- Ron’s Birthday (March 1st) - poisoned
- Eats chocolate that Romilda Vane gave to Harry (love potion) → Harry takes Ron to Slughorn for antidote → Ron collapses after drinking a cup of mead
- DD mad w/ Snape for some reason, wants him to investigate Slytherin (necklace & poison incidents are related?) (Snape reluctant to kill DD?)
- Harry skull fracture in Q game against Hufflepuff (w/ LL commentating)
- McLaggen missed bludger coming to Harry
- Harry makes Kreacher & Dobby follow Malfoy bc Malfoy disappearing on Marauder’s Map sometimes
- Malfoy in Room of Requirement with Crabbe & Goyle watching out (disguised as girls w/ polyjuice potion)
- Mundungus sent to Azkaban
- Aragog’s funeral (Harry extracts Slughorn’s memory)
- Harry drinks small portion of felix felicis
- Gets Slughorn to go to Aragog’s funeral (spider venom is very valuable)
- Hagrid & Slughorn get drunk → Slughorn gives memory in bottle to Harry
- Hermione pass apparition exam, Ron almost did by half an eyebrow
- Horcruxes (explained in Slughorn’s real memory)
- Horcruxes are hidden part of one’s soul
- One has to kill to create a horcrux
- V chose horcruxes > elixir of life (philosopher’s stone) b/c elixir of life has to be drunk periodically (if smth happened to it, he’d die)
- V only had 6 horcruxes before killing Harry, wanted to use Harry’s death to create his last horcrux
- Horcruxes
- Diary
- Convinced DD that V had more than one b/c he wouldn’t let diary be destroyed so easily if he only had one
- V told Lucius to have diary in Hogwarts → V “died” b4 telling Lucius what it was → gave diary to Ginny in hopes of getting DD kicked
- Lucius’ fault that diary was destroyed
- Sorvolo’s ring, destroyed by DD using Sword of Gryffindor
- Found in ruins of Gaunts’ house
- Slytherin Locket
- Hufflepuff’s Cup
- Ravenclaw Diadem
- Harry Potter
- Nagini
- DD been missing from Hogwarts often b/c he was in search of V’s Horcruxes
- Sectumsempra on Draco
- Harry finds Draco crying in bathroom → uses Sectumsempra (prince’s secret spell) w/out knowing what it did → Snape saves Draco’s life
- Punishment w/ Snape for rest of the year
- Hid Prince’s book in RoR that contained other forbidden/hidden objects (The Room of Hidden Things - same place where Ravenclaw’s Diadem was hidden)
- Missed Q championship → Gryffindor won anyways 450-140, Harry kisses Ginny in party
- Harry finds out that Snape was DE who revealed prophecy to V through Trelawney
- Harry & DD Horcrux mission
- Apparated to rocky shore ocean where V used to bully orphans
- Entered cave → crossed lake after DD brought to surface boat that V hid
- Drank content of cauldron to reveal Horcrux in it → DD super weak → Harry fight off inferi → DD save him w/ ring of fire
- Death Mark above Hogwarts
- Draco got DE to enter Hogwarts after realizing that cabinet Montague was stuck in last year was transportation method between Borgins & Burkes and Hogwarts
- Montague could sometimes hear sounds at both B&B and Hogwarts → tried to apparate away, got stuck in toilet
- Draco’s plan + DD’s death
- Used imperius on Madam Rosmerta (Three Broomsticks) to give necklace to Katie and poison Slughorn’s mead
- Heard Hermione say in library that Filch doesn’t know how to distinguish mead
- Communicated with Rosmerta with Enchanted Coins
- Rosmerta warned Draco that DD left Hogwarts (saw him at Hogsmeade) → Draco cast Death Mark to bait DD to come back and wait to kill him
- Draco hesitant to kill → Snape kills DD (under DD’s orders? also fulfills vow)
- DD knew what Draco was doing the whole time, didn’t confront him b/c V would kill Draco if he knew DD suspected him
- Note in Horcrux locket that R.A.B already destroyed real one → DD died for nothing
- Snape is Half-Blood Prince
- Eileen Prince mother, muggle Tobias Snape father
- Bill bit by Greyback - not during full moon → develops liking for (almost) raw steak
- Tonks likes Lupin, Lupin thinks he’s too old & dangerous (werewolf) for her
- Draco used Hand of Glory (gives light only to holder) to escape being caught in RoR
- DD funeral + aftermath
- Snape didn’t accuse Harry of having his potions book b/c didn’t want DD to find out
- Where did DD learn Mermish (merpeople language)?
- Harry can’t be together w/ Ginny, too risky w/ Voldemort
- Will go to Godric’s Hollow - home of Godric Gryffindor, DD family, and Potters
- Where first snitch was made by Bowman Wright
“Harry Potter y las reliquias de la muerte”
- Tonks is sister of Narcissa and BL, recently married Lupin
- Charity Burbage hung, killed, eaten by Nagini
- Professor of Muggle Studies at Hogwarts
- V needed to borrow Lucius’ wand?
- Elphias Doge (went to Hogwarts with DD)
- Recounting memories with DD in newspaper
- DD entered Hogwarts shortly after father Percival Dumbledore was charged with muggle assault
- Ariana (squib sister) and Kendra (mother) died too, only Aberforth who lived in his shadow
- DD discovered 12 uses of dragon blood
- Famous duel with Gellert Grindelwald
- Hestia & Dedalus (Order members) escort Dursleys away from Privet Drive
- Dudley thanks Harry for saving his life, end on high note 😀
- Polyjuice potion to have 7 Harrys (paired up with member of Order) flying on brooms
- Real Harry goes w/ Hagrid on Sirius’ motorcycle
- Encountered DE’s and realized who real Harry was b/c of signature Expelliarmus spell on Stan Shunpike (under imperius)
- Hedwig dies 🕊️
- Fly to Tonk’s parents’ house → portkey to The Burrow
- George missing an ear, Moody died, Mundungus missing
- How did Harry’s wand act upon itself?
- How did DE’s know they were leaving at that time?
- Snape told V (undercover for DD) when they were leaving, also told Mundungus to suggest 7 Potters strategy to Order
- The Burrow = new Order HQ
- Hermione give Harry Sneakoscope as birthday gift (old one Ron gave him was broken)
- Hermione + Ron measures taken for sake of Horcrux mission
- Hermione memory spell on parents to move to Australia, forget that they have a kid
- Mr. W + F&G adorn Weasley Family Ghoul with Ron’s PJ’s, pretending to be Ron with Spattergroit
- Hermione Accio’s Horcrux books from DD office after DD funeral
- Horcruxes can only be destroyed by powerful/destructive substances (e.g. basilisk venom)
- Owner has to shown genuine regret to connect soul again
- Soul in Horcrox cannot be transferred to another object
- Can possess someone else if they get too emotionally attached (e.g. Ginny w/ diary)
- Hagrid gave Harry Mokeskin pouch as birthday gift - only owner can open
- Bill (Wililam Arthur Weasley) and Fleur’s wedding
- Presented to them by Scrimgeour (accompanying Arthur Weasley)
- Deluminator to Ron (designed by DD, make lights in certain area go off, turn back on with click)
- Book The Tales of Beedle the Bard written in ancient runes language to Hermione
- Beedle the Bard is children’s author for wizards
- Sword of Gryffindor to Harry
- Didn’t give b/c still needed it to destroy horcruxes → made a fake copy to keep in Snape’s office
- Left real one
- Harry’s first caught snitch to Harry
- Snitch has flesh-memory, can hide objects inside snitch for person that touched it first (why snitch-makers use gloves when making)
- “I open at the close” engraved when Harry puts it near mouth (was snitch he almost swallowed in 1st year)
- Krum tells Harry that Xenophilius Lovegood (LL’s father) wearing necklace w/ Grindelwald symbol (Grindelwald went to Durmstrang)
- Aunt Muriel’s version of DD’s family history
- Ariana was squib, locked in basement of family in Godric’s Hollow for not being able to do magic
- Kendra died first (Ariana killed Kendra?)
- DD did not defend himself from accusations
- Bathilda Bagshot still lives in Godric’s Hollow (History of Magic author)
- Shacklebolt patronus message: Scrimgeour dead, ministry has fallen to DE → H&R&H apparate to Tottenham Court Road
- Encounter DE’s in cafe → stun and erase memory → apparate to GP
- R.A.B is Regulus Acturus Black
- Under V, ordered Kreacher to test (drink) poison in cauldron in cave where locket was going to be stored
- Later, RAB ordered Kreacher to replace locket w/ fake, RAB dies after drinking poison to reveal it
- Kreacher couldn’t destroy real one → stolen by Mundungus → gave to Umbridge
- DE’s have taken control over ministry and Daily Prophet, get public to help find Harry
- V didn’t directly become minister → invokes fear and uncertainty in public
- Pius Thicknesse is new minister, under imperius
- Mandatory to attend Hogwarts → V have all wizards under control
- Punish wizards who come from muggle families “stolen magic”
- Lupin wants to accompany them on Horcrux mission, Harry realizes that he’s dodging responsibility of staying w/ Tonks and their kid
- Snape new Hogwarts director, new Muggle/DaDA teachers are DE’s (Carrow siblings)
- Voldemort wants Gregorovitch (wand maker)
- Hermione hid Phineas Nigellus (Professor Black) portrait in her bag to prevent him from snitching their location away
- Ministry infiltration
- Polyjuice potions, become separated immediately after Ron forced to fix rain in office to save his wife’s life, Hermione taken by Umbridge
- Harry attacks Umbridge during trial of Ron’s wife Mrs. Cattermole → yank Umbridge’s real Slytherin locket → save muggles → escape to forest b/c Yaxley was holding onto Hermione’s arm, saw GP
- Harry also took Moody’s eye that Umbridge took to vigilate her office with on door
- Escape to forest where Quidditch World Cup was held
- Can feel small heartbeat in locket (horcruxes’ souls can be felt)
- Voldemort vision
- Torturing Gregorovitch for Elder Wand
- Legillimency on Gregorovitch → saw that Grindelwald stole it → V killed Gregorovitch
- Buried Moody eye under tree
- Take turns holding horcrux to not let it weaken them too much over long time
- V hid in Albania during exile
- Overheard Ted Tonks (not pure blood), Dean (not sure), and some goblins on the run talking
- Sword of Gryffindor moved to BL’s Gringotts vault from Snape’s office (goblins found out it was fake)
- Where is real one?
- Interrogate Phineas Nigellus → DD used sword before to open ring → sword can destroy horcruxes
- Ron’s pissy mood
- Spoiled by having good food every day, place to sleep
- Mad at Harry b/c thought he had a plan or DD told him what he needed to do
- Rage quit while raining, Hermione crying :<
- Grindelwald symbol in The Tales of Beedle the Bard
- Realize Godric Gryffindor is from GH → did DD leave real sword w/ Bathilda?
- Christmas in Godric’s Hollow
- Apparate to GH under polyjuice from muggles
- Peaceful, snowing scene where Harry & Hermione explore cemetery
- Kendra & Ariana Dumbledore gravestone
- “Where your treasure is, there will your heart be also”
- James & Lily Potter gravestone
- “The last enemy that shall be destroyed is death”
- Died on Halloween
- Enter Bathilda’s house → Bathilda turns into Nagini, ordered by V to retain Harry there until he arrives
- Escape after Hermione landed explosive spell → broke Harry’s wand
- The Life and Lies of Albus Dumbledore by Rita Skeeter
- Taken from Bathilda’s house
- Used Veritaserum on Bathilda to extract “true” information on DD’s backstory
- Bathilda was Grindelwald’s great-aunt → connected him w/ DD when DD came back to GH after receiving news of Kendra’s death
- DD letter to Grindelwald - use power (magic) to control/rule muggles
- Dumbledore gave rise to Grindelwald’s evil reign?
- Friendship only lasted 2 months
- Aberforth blamed DD for Ariana’s death
- Grindelwald fled country few hours after death
- Nurmengard - prison that Grindelwald made to capture his opposition, died in it after DD captured him
- Harry mad DD never told him any of this
- Apparate to Forest of Dean
- Deer patronus (Snape’s) appeared while Harry was on guard → followed it to frozen pond with Sword of Gryffindor at bottom → undressed himself and submerged himself to retrieve it → saved by Ron (who was lurking in forest and came because of deer)
- Harry tell horcrux to open using parseltongue → Tom Ryddle spills Ron’s greatest fears → fake Harry & Hermione emerge from eyes of locket and start making out
- Ron destroys it finally
- Hermione scold Ron like his mom, wanted to be mad at him
- Ron’s story
- Wanted to come back right after he ditched
- Lived at Shell Cottage - Bill & Fleur’s new house
- Came across band of Snatchers - ppl who capture muggles and blood traitors (pro-Muggle pure bloods) for ministry compensation - and told them he was Stan Shunpike → managed to escape
- Yanked wand, gave it to Harry
- Hermione’s voice from Deluminator
- Heard Hermione’s voice from Deluminator when she mentioned his name abt being unable to fix Harry’s wand
- Used it and ball of light went inside him → enlightenment, knew where to find H&H
- Apparated to snowy mountains where H&H were, but couldn’t hear or see them b/c of protective spells
- Apparted to this Forest of Dean
- Pronouncing V’s name breaks protective spells (DE’s use this to locate Order members)
- Ottery St. Catchpole - ask XL abt Grindelwald symbol
- Erumpent horn - dangerous, explode upon touch
- “Grindelwald symbol” = Deathly Hallows symbol
- The Tale of the Three Brothers in The Tales of Beedle the Bard
- Three brothers use dark magic to cross river
- Death stops them halfway (b/c/ they were supposed to die) → gives oldest brother Elder Wand, middle brother Resurrection Stone, third brother Invisibility Cloak
- Death kills oldest brother w/ Elder Wand while sleeping
- Death kills middle brother by suicide after realizing his resurrected lover acted like a ghost
- Death never found third brother, died of old age after giving son the cloak
- Deathly Hallows (Elder Wand, Resurrection Stone, Invisibility Cloak)
- If combined → owner can conquer death
- Elder Wand
- To be true owner, must defeat previous owner (kill/disarm)
- Peverell family (name on grave in GH w/ DH symbol)
- Three Peverell brothers theorized to have been three brothers in tale: Antioch, Cadmus, Ignotus Peverell
- XL betrayal + Luna being hostaged
- Harry finds paintings of him, Ron, Hermione, Ginny, Neville in Luna’s room → realizes no one’s been in the room in ages
- Luna being held hostage by ministry b/c/ XL supported Harry in The Quibbler, XL called ministry to come capture Harry
- Escape after Hermione created hole in ground to fall through (she & Ron in cloak) so ministry could see Harry → know XL wasn’t lying → spare XL’s life
- Sorvolo Gaunt said that his ring was from Peverell family, there was a stone on it (Resurrection Stone?)
- Dumbledore borrowed invisibility cloak the night Harry’s parents died → inspected it to check if it was Deathly Hallow?
- Harry descendant of 3rd Peverell brother
- V is after Elder Wand but doesn’t know that it’s a deathly hallow
- Why he captured Ollivander, killed Gregorovitch
- Potterwatch - radio program by Lee Jordan, gives actual information instead of propaganda e.g. other ministry programs
- Ted Tonks died
- Connect to outside world for 1st time in long time
- Harry says V’s name → caught by Greyback’s Snatchers
- Dean and Griphook (goblin) captured too
- Hermione spell on Harry to make him unrecognizable temporarily
- Taken to DE HQ (Malfoys’ home)
- DE’s trying to determine if real Harry or not → Draco keeps saying “I don’t know”
- Taken to basement w/ Ron, Dean, Griphook; Hermione interrogated (tortured)
- Encounter Luna and Ollivander
- BL thinks they infiltrated her Gringotts chamber to yank sword → ask Griphook → Griphook caps, saves H&R&H
- Pettigrew killed by own silver hand
- After hesitating to kill Harry
- V enchanted it to strangle him if he showed slightest hesitation in following orders
- DD predicted “The time may come when you will be very glad you saved Pettigrew’s life” (Harry prevented Lupin & Sirius from killing him in 3rd book)
- Dobby comes to apparate Ollivander, Luna, Dean away → comes back and apparates w/ H&R&H → dies by dagger wound under starry sky close to Shell Cottage
- “Here lies Dobby, a free elf”
- Weasleys + Ollivander moved from The Burrow to Muriel’s house (DE’s know Ron is w/ Harry)
- Griphook interrogation
- Harry wants to infiltrate BL’s vault, another horcrux in there? (cup)
- Griphook wants sword in exchange → Harry agrees to give it once all horcruxes all destroyed (not specified, of course)
- Has to be careful b/c/ goblins believe that true owner of object is fabricator, wizards are nothing more than robbers
- Told V that bond between his & Harry’s wands can be broken by using another wand → borrowed Lucius’ wand
- Told V that Gregorovitch had Elder Wand
- Grindelwald was robber that stole Gregorovitch’s Elder Wand → rose to power, DD realized he was only one that could stop him → duel → Elder Wand is in Hogwarts now (DD is owner)
- Harry godfather of Edward “Teddy” Remus Lupin (named after Ted Tonks)
- Yanked BL, Draco, and PP’s wands
- V snatches Elder Wand lying on DD’s corpse in grave…
- BL’s vault infiltration
- Hermione polyjuice to BL, Ron disguised via Hermione’s spells, Harry & Griphook under invis. cloak
- Meet DE Travers → Harry imperius on him and goblins to pass identification (goblins were warned that ppl might imposter BL)
- Polyjuice/imperius nullified by Thief’s Downfall
- BL treasures protected by Flagrante and Gemino spells → multiply and catch fire every time they were touched
- Yanked Hufflepuff’s Cup on top of pile → escape on Gringott’s Dragon → jump into lake
- Lost sword to Griphook
- V vision
- Harry entered V’s mind, finds out a horcrux is in Hogwarts
- V wants to check all horcrux hiding places to make sure they’re there → H&R&H go to Hogwarts
- Saved from DE’s by Aberforth (Hog’s Head bartender)
- Aberforth had other half of Sirius’ mirror from DD → sent Dobby to save Harry in Malfoy’s home
- Truth about Ariana’s childhood
- Tramatized after getting bullied by 3 muggles after forcing her to teach them magic but not being able to do it → Percival (father) sent to Azkaban for muggle assault
- Couldn’t control magic → accidentally killed Kendra (mother)
- Aberforth fight w/ DD & Grindelwald → Ariana dies somehow during fight
- Ariana painting brings Neville → leads H&R&H to RoR w/ other Hogwarts friends
- Carrow catches Harry & Luna in Ravenclaw commons → invokes Death Mark
- Percy appears calling himself an idiot, back on good terms w/ family
- Ron & Hermione go to Chamber of Secrets → take basilisk fang and destroy Hufflepuff’s Cup
- Ron entered by imitating Harry’s parsilisk noises until it worked
- Ron & Hermione kiss ❤️🔥
- Search for Ravenclaw’s Diadem
- “Wit beyond measure is man’s greatest treasure”
- Grey Lady’s story (Ravenclaw ghost)
- Helena Ravenclaw (daughter of Rowena Ravenclaw)
- Stole diadem from mother, told Tom Ryddle where it was
- The Bloody Baron (current ghost) was sent to take her to visit her mother on deathbed → hid diadem in Albania
- BB stabs Helena → suicides afterward
- Harry realizes V hid diadem in Hogwarts on night he asked DD for position → diadem is in The Room of Hidden Things (RoR)
- Same place where he hid old Half-Blood Prince’s potion book
- Encounter Draco + Crabble + Goyle
- Crabbe invokes Fiendfyre → burns everything up → he dies in his own fire, Harry saves Draco + Goyle using brooms
- Diadem already destroyed by fire
- Fred, Tonks, Lupin deaths
- Whomping Willow (Snape’s death)
- V realizes Elder Wand won’t work b/c/ Snape was one who killed predecessor (DD)
- V orders Nagini to kill Snape
- Harry extracts silvery substance from Snape
- Pensieve - Snape’s memories
- Snape introduced Lily to magic world
- Petunia’s hate for magic
- Didn’t get invited to Hogwarts like Lily
- Lily & Snape reading her rejection letter → all wizards are snoops
- Shared Hogwarts Express compartment w/ Lily, James, Sirius
- DD & Snape’s plan to protect Harry
- Snape told V prophecy b/c thought it was about Lily
- DD: If you truly loved Lily, you’d protect Harry → Snape agrees
- DD told Snape to kill him to protect Draco
- Didn’t want to ruin Draco’s innocence by letting him kill DD
- Draco’s mission to kill D was punishment for his parents, V never believed he would actually complete it
- Part of V’s soul was in Harry → only way to beat V was V killing Harry himself
- Real reason why they protected Harry
- Give real sword to Harry with deer patronus
- Harry opens snitch by telling it he’s on the verge of death → gets Resurrection Stone → goes to Forbidden Forest (where V is) accompanied by Lupin, Sirius, James, Lily
- V “kills” Harry w/ Elder Wand (but Harry was true owner, so didn’t actually die)
- Afterlife in King’s Cross - talk w/ Dumbledore
- No glasses, no scar, helpless whining creature
- Harry is the 7th horcrux
- As long as V is alive, Harry is alive
- V resurrected his body using Harry’s blood
- V’s body has tiny part of Lily’s spell (as long as that spell is still alive, Harry will never die)
- DD was greedy, power-hungry young boy w/ Grindelwald who wanted Deathly Hallows
- Fought w/ Grindelwald b/c Grindelwald didn’t want DD to pursue DH’s with ill sister
- Rejected minister position b/c didn’t trust himself w/ power
- Harry is real master of Deathly Hallows - used them not for power, but with humility
- True owner wouldn’t be scared of death
- DD knew V would look for Elder Wand after he lost duel to Harry in Little Hangleton (labyrinth)
- V asks Narcisa to confirm if Harry dead → whispers to Harry if Draco is still alive → Harry says yes → Narcisa lies and says Harry is dead
- Only way to go to Hogwarts and find Draco
- Harry is real owner of Elder Wand
- Draco became EW owner when he disarmed DD (unbeknownst to him)
- Harry disarmed Draco later on and took his wand → ownership became Harry’s
- Shacklebolt new minister
- Harry uses Elder Wand to fix old wand → puts it back in DD’s tomb
- Resurrection Stone lost in forest
- 19 Years Later
- James - prankster, much like original James Potter
- Albus Severus - cautious, thoughtful
- Lily
- Neville is herbology professor
역사历史historiahistory
Siege of Numantia
- Ancient Celtiberian settlement who didn’t surrender to conquest of Rome (135 BC), who sieged their city → famine in city and many chose to starve instead of being enslaved
- Spanish: Numancia
Eyam
- English village that isolated itself to prevent infection spreading after bubonic plague was discovered there in 1665
- Half of Eyam villagers survived
동물动物animalesanimals
Cymothoa exigua
- Parasite “tongue-biter”
- Suck blood/flesh out of fish tongues and replace the tongue functionally
- Males camp out in gills, transition to female when female tongue-biter dies
- Sometimes latches onto female tongue-biter to mate
Leucochloridium paradoxum
- “Green-banded broodsac”
- Parasite that takes control of snail eyes → motors “zombie snail” under broad daylight so birds mistake them for maggots → eat snails
- Reproduce inside bird stomachs → poops out which other snails eat to repeat process
cosas de informatica
SQL vs NoSQL Databases
- SQL (Structured Query Language)
- Table-based
- Vertically scalable (increase size of instance)
- Relational databases
- Transactions are acid compliant
- Atomic (groups of statements are either all run or none)
- Consistency - data valid before and after
- Isolation - multiple transactions at same time
- Durability - committed data never lost
- Columns and tables must be created ahead of time → more time to set up
- Not effective for storing unstructured data
- Document-key, graph, wide-column stored
- Horizontally scalable (increase # of instances)
- Better for storing unstructured data
- Designed for distribute use cases → loss of strong consistency (small delay in updating) eventual consistency
PostgreSQL vs MySQL
- Relational database management systems (RDBMS)
- Rely on SQL (structured query language)
- Support JSON
- Easy to use, web applications
- Read-heavy workloads
- More complex queries and data types
- JSON support is embedded into system, efficient storage and querying of JSON data
- Write-heavy workloads
Relational databases
- Composite key is primary key but with multiple values
DevOps
- Set of practices that combines software development (Dev) and IT Operations (Ops)
- Continuous Integration / Continuous Delivery (CI/CD)
- Auto-deploy website whenever I push to main e.g. push → Github → Vercel → deploy
- Auto-run tests for each pull request
- Containerize packages, apps, and dependencies into isolated containers for consistency
SSL Certificate
- SSL = Secure Sockets Layer
- Technology that encrypts data being passed from web browser to servers
- Protects data, owner verified
- Url updated from http to https (s stands for secure)
Deep Learning - “Deep Learning: Foundations and Concepts” by Christopher Bishop and Hugh Bishop
- The Deep Learning Revolution
- Unsupervised (no labels, e.g. pictures, music, text, audio) vs supervised (labels)
- Self-supervised learning - outputs derived from input training data without needing separate human-derived labels
- Prediction for target variable
- Overfitting - model too closely aligned to training data, poor representation of new data
- 1) increasing size of data set
- 2) regularization - adds penalty term to error function to not have large magnitudes for coefficients
- Hyperparameter - fixed values during minimization of error function to determine model parameters
- Cross-validation - divide training data into S subsets → train model on S-1 subsets, test on remaining subset → repeat S times and take average
- Error backpropagation - evaluating derivative of error function by using gradient-based optimization techniques (e.g. stochastic (random) gradient descent)
- Deep learning - focus on deep neural networks (many layers of weights)
- Bayesian perspective - use of probability as quantification of uncertainty
- More results we observe → lower uncertainty
- Includes frequentist probability as special case
- Probability in terms of frequency of repeatable events

- Prior (probability observed before test) vs posterior possibilities
- Covariance denotes how two variables vary together (if x and y are independent, then covariance is 0)
- n-order moments (expectation of x raised to power of n)
- Maximum likelihood estimation
- Used to estimate parameters from observed data that makes observed data most likely → can lead to over-fitting
- Can have bias bc measured relative to sample mean and not true mean
- Equivalent to minimizing sum-of-squares error
- Contrasts with Bayesian inference which produces distributions of parameters based on both observed data and prior information about likely values of parameters
- Entropy in terms of avg amount of information needed to specify state of random variable
- Less probable → more information
Deploying Flask Backend (https://www.animales.click)
- Tried using AWS EBS (Elastic Beanstalk) but too complicated
- Tried using PythonAnywhere
- Could’ve worked, but free tier didn’t have enough space to download pytorch
- Deployed using AWS EC2 instance with Deep Learning AMI
- EC2 needed to be associated with public subnet to connect on Bash console
- Pytorch was preinstalled as conda environment
- Deployed files onto instance via nginx, could be accessed via public ip address
- Needed SSL certificate for Vercel to access it (since Vercel was https)
- This required domain name → Namecheap https://3127489327489.store/
- Used AWS Route53 to connect with Namecheap domain
- Downloaded SSL certificate with certbot
Getting SSL certificate on yangba.net
- Use root domain and *.[root domain] for SSL certificate domain names
- DNS verification in for SSL certificate → add to DNS with appropriate CNAME name and value (can change later to CloudFront url)
- Alternate domain names in CloudFront must be covered by SSL certificate and match CNAME record names in Route 53
- These CNAME record names must have value of CloudFront distribution domain name
CPU vs GPU
- Minimal latency, often referred to as brian of the computer
- Arithmetic & logic units (ALU), Control Unit, Cache
- Memory (not part of CPU but used to store instructions that CPU uses)
- Multi-core CPU
- Runs serially
- Originally invented to help render images on display devices (gaming)
- Handles high throughput
- Hundreds/thousands of cores → parallel processing
- Also excel in ML, financial simulations, scientific computations, AI
- High-computing devices
Process vs Thread
- Instance of program that’s being executed
- Includes code segment, data segment, heap, stack, registers
- Separate memory space → one process cannot corrupt another process
- E.g. Chrome tabs
- Unit of execution within a process
- Single-threaded process—process with one thread
- Multi-threaded process—process with more than one thread
- Each thread has independent registers and stack
- All threads share heap, code segment, data segment
- Efficient communication between threads
- E.g. Apache Server
- Downsides
- One thread can corrupt entire process
- Race conditions
- No two threads of same process can run concurrently
- However, two processes can run concurrently
- Multithreading: best for I/O-bound e.g. waiting for API calls, user input, reading/writing files
- Multiprocessing: best for CPU-bound e.g. embedding generation, heavy parsing, text processing
Firestore
- Collections and documents
- Collection: like a database, container that holds many rows/files
- Document: specific “row” within database
- E.g. collection named “students” has document with unique document ID with fields e.g. name, age, email, password, etc.
- set() allows you to set unique identifier, add() automatically creates one
OAuth 2.0 (Open Authorization 2.0)
- E.g. user uploads photos to SnapStore and wants to print them using PrintMagic
- Resource owner (owns photos)
- Resource server (stores photos, accepts and validates access token by client)
- Authorization server (receives requests from client to issue access tokens upon successful authentication and consent by resource owner)
- Client (system that requires access to protected resources)
- Redirects user to Authorization Server for them to enter password
- Must hold access token

- Allows users to grant third-party applications access to data without sharing credentials (e.g. username and password)
- Access tokens have expiration time (can also be revoked by user at any time)
- Users grant scopes (permissions) to applications
- E.g. only access photos, not profile
- E.g. Github with Google SSO
- Initiate login on Github
- Github = client
- Github redirects browser to Google
- Github constructs special url with client_id, redirect_uri, scope, etc.
- User authenticates and grants consent on Google
- Enters username and password
- Google displays consent screen: “Github wants to access…”
- Google sends authorization code back to Github
- Google’s authorization server redirects back to Github’s specified redirect_uri, which contains authorization code
- Github exchanges authorization code for access token
- Google issues access token
- Validates authorization code and sends response back that contains access token
- Github uses access token to access google data
- Sends access token in Authorization header of API requests to Google (e.g. Authorization: Bearer <access_token>
- Github logs user in
- Google’s resource server returns requested user data and Github uses this to log in / create new account
- E.g. Next.js + Django + Firebase
- User is resource owner
- Next.js is client
- Firebase is authorization server
- Django is client to Firestore, resource server to Next.js
- Firestore is resource server
JSON Serialization
- Bytes cannot be encoded as UTF-8 strings for JSON → have to encode it into Base64 → convert (decode) to UTF-8 string
base64.b64encode(byte_image).decode(‘utf-8’) //valid for JSON serialization
if __name__ == “__main__”:
- Every Python file has built-in variable called __name__ → set to “__main__” by interpreter when file is run directly
- If imported as module, __name__ is set to module’s name
- Allows for modularization, test functions by running file but also reuse by importing to other scripts
Deep Learning Crash Course
Deep Learning Crash Course for Beginners
- ML technique that learns features directly from data (no human intervention)
- Learning flow: initialize parameters randomly → feed input data → compare pred with expected value & calculate loss → backpropagation → update parameters based on loss → repeat until loss is minimized
- Activation function
- Decides whether neuron passes threshold to contribute to next layer
- Step function—binary value, not optimal if deciding best one among multiple candidates
- Linear function—derivative is constant, change rate doesn’t depend on input during bp
- Last hidden layer is just linear function of all other hidden layers → can be just written as single layer
- Sigmoid function—1/(1+e^-t), commonly used
- Non-linear, analog outputs (continuous), range: (0, 1)
- Vanishing gradient problem (if input is super small or large, the gradient becomes super small)
- Good for classification problems
- Tanh function—(e^z - e^-z) / (e^z + e^-z)
- Non-linear, derivative steeper than sigmoid, range: (-1, 1)
- Vanishing gradient problem
- ReLU Function (Rectified Linear Unit)
- R(z) = max(0, z)
- Non-linear, sparse activations, range: [0, inf)
- Dying ReLU Problem (gradient is 0 for negative values)
- Leaky ReLU (y = 0.01x)
- Parametric ReLU (y = ax)
- Regression: squared error, Huber loss
- Binary Classification: binary cross-entropy, Hinge loss
- Multi-Class Classification: multi-class cross-entropy, Kullback Divergence
- Gradient Descent: Iterative steps toward minimizing loss based on calculating gradient for each neuron → use small learning rate (e.g. 0.001)
- Stochastic Gradient Descent (SGD)—uses subset of training examples and momentum to accumulate gradients → less computing power
- Adagrad (adapts LR to individual features), RMSprop (specialized version of Adagrad, accumulates gradients in fixed window), Adam (Adaptive Moment Estimation)
- Parameters and Hyperparameters
- Parameters are not set manually, estimated from data (e.g. weights, biases)
- Hyperparameters are manually set, no clear-cut way to find best value (e.g. learning rate)
- Epochs, Batches, Iterations
- Epoch: when entire dataset is passed forward and backward through NN once
- More epochs → helps generalizability (risks overfitting)
- No right # of epochs
- Iterations: number of batches for one epoch
- 34000 examples with batch size of 500 → 68 iterations to complete 1 epoch
- Supervised Learning: Trained on labeled data
- Classification—linear classifiers, support vector machines, K-nearest neighbors, Random Forest
- Regression—linear regression, Lasso regression, multivariate regression
- Finds relationship between dependent & independent variables
- Goal: predict continuous value e.g. test scores
- Goal: find relations between data points
- Unsupervised Learning: manifest underlying patterns in data
- Clustering—K-Means, Expectation Maximization, Hierarchical Cluster Analysis (HCA)
- Partitional clustering, hierarchical clustering
- Attempts to find relationships between different entities (e.g. market basket analysis)
- Enables agent to learn interactive environment through rewards & punishments
- Modeled as Markov Decision Process
- Goal: find action model to maximize total cumulative reward
- Regularization (tackling overfitting)
- At every iteration, randomly selects nodes and removes some nodes and connections → different set of outputs
- Add fake data by transforming existing dataset to synthesize more data (e.g. rotating, scaling image)
- Training error decreases steadily
- Stop training when validation error starts to increase (overfitting starts to appear)
- Neural Network Architectures
- Fully-Connected Feed Forward NN
- Each neuron is connected to every subsequent layer with no backward connections
- Fixed-sized inputs → fixed-sized outputs
- Vanilla NN can’t handle sequential data
- Uses feedback loop in the hidden layers
- Backpropagation applied for every sequence data point (Backpropagation Through Time BTT)
- Short-term memory due to VGP
- CV, image recognition, image segmentation, etc.
- Input: 2D array of neurons (e.g. pixels), output: 1D
- Convolution: allows us to extract visual features in chunks
- Pooling: reduce # of neurons necessary in subsequent layers
- Steps: convolve the image → pool the result → repeat → add few layers to classify image → prediction in output layer
- 5 Steps in Creating a Deep Learning Model
- Gathering Data
- IRIS Flower Dataset ~ 150 images
- Google Translate ~ trillions of examples
- Amount of data ~ 10x # of model parameters
- Preprocessing
- Split into subsets—train-test-validation splits
- More hyperparameters → larger validation set
- Cross-Validation
- Training
- Feed data → forward propagation → loss function → backpropagation
- Evaluation
- Test model on validation set
- Optimizing
- Hyperparameter Tuning e.g. increase # of epochs adjust learning rate
- Regularization, data augmentation (more data)
Multicollinearity
- Two independent variables are highly correlated → makes it difficult for regression model to determine unique contribution of each variable to dependent variable
pd.get_dummies() = ONE-HOT ENCODING
K-fold Cross Validation
- Divide training data into k folds (subsets) → train on k-1 folds to test on remaining 1 fold → repeat k times for each fold → result in k accuracy scores (can compute mean for single metric)
Tuning vs Fine-Tuning
- Tuning changes hyperparameters → optimize performance
- Fine-Tuning changes weights/parameters on deep learning models → adapt pretrained model to specific task
CS148 Project ML
Linear regression vs logistic regression
- Linear regression models linear relationship (continuous values)
- Logistic regression uses S-shaped curve (sigmoid) to estimate probabilities for discrete classes
- Better model for predicting win probability
- Doesn’t require GPUs because relatively lightweight for small to medium datasets
Scikit-learn methods
- model.predict() vs model.predict_proba()
- predict() returns discrete class
- predict_proba() returns probability array per sample (better for win probability)
Joblib
- Python library for serialization (freezes Python object → saves to disk to load back up later)
- For logistic regression model, just serializes Python object into learned weights and biases
- Joblib better than .pickle for large NumPy arrays
XGBoost (eXtreme Gradient Boosting)
- Sequential trees, each with specified depth
- Classification
- Calculate similarity scores and gain to determine how to split data
- Similarity scores calculated using residuals and input-specific predicted value (initially randomized for all inputs)
- Prune tree by calculating differences between gain values and hyperparameter gamma
- If negative, prune and work up the tree; otherwise nothing
- Calculate output values for leaves
- Lambda is regularization parameter → if lambda is smaller, more pruning and smaller output values
- Minimum # of residuals in leaf is related to metric cover, which is denominator of similarity score minus lambda
- Similarity score

- Calculate similarity scores and gain to determine how to split data
- Pruning + regularization (lambda)
- Similarity score
swar/nba_api timeout error
cosas de llms
Hands-On LLMs
Ch1: An Intro to LLMs
- History of Language AI (NLP)
- Bag-of-Words (first mentioned around 1950s, popular in 2000s)
- Tokenization → vocabulary → count # of times word appears in each sentence
- Ignores semantic nature
- Embeddings: learned from training on lots of textual data e.g. Wikipedia
- Leverages neural networks to learn relationship between two words
- Used for two tasks: encoding and decoding (autoregressive)
- Can add attention mechanisms to decoder step to pass in hidden states of all input words
- Could be trained in parallel → tremendous speed-up compared to RNNs
- Self-attention → encoder attention → feed-forward NN
- BERT (Bidirectional Encoder Representations from Transformers)
- Encoder-only
- Representing languages, trained by masked language modeling
- Commonly used for transfer learning: pretraining it for language modeling and then fine-tuning it for a specific task (e.g. classification, NER, paraphrase identification)
- GPT-1 (Generative Pre-trained Transformer)
- Decoder-only, 117m parameters
- Large generative decoder-only models are usually known as LLMs
- VRAM (video random-access memory) is important
- GPU-poor: those without a powerful GPU
Ch2: Tokens and Embeddings
- 3 main steps that dictate how tokenizer breaks down input prompt
- Tokenization method
- Word, subword, character, byte
- GPT-2 tokenizer represents special characters (e.g. Chinese characters) by multiple tokens (all look identical i.e. question mark black box) but stand for different tokens
- GPT-4 tokenizer has specific token for every sequence of whitespaces up to 83
- Tokenizer design (parameters)
- Vocabulary size (e.g. 100K)
- Special tokens
- Capitalization
- Dataset to be trained on
- E.g. code-focused models more optimized toward encoding code by making different tokenization choices
- Sliding window with window size n (# of neighbors on each side of central word)
- Used to train neural network to predict if words commonly appear in same context or not
- Skip-grams: method of selecting neighboring words
- Negative examples: adding negative examples by random sampling from dataset
Ch3: Looking Inside LLMs
- Autoregressive: After each token generation → tweak input prompt for next forward pass by appending output token to end of the input prompt
- Decoder transformer blocks (which make up most text generation models)
- In each pass: tokenizer breaks down input into token IDs → followed by stack of Transformer blocks that do all the processing → followed by LM head which translates output of stack into probability distribution
- Each transformer block includes attention layer and feedforward NN (multilayer perceptron i.e. mlp)
- Different kinds of LM heads: sequence classification heads, token classification heads
- Decoding strategy: method of choosing single token from probability distribution
- Parallel Token Processing
- Tokenizer breaks text into tokens → each input token flows through its own computation path
- Context length: limit for how many tokens they can process at once
- Only output result of last stream is used to predict next token (influenced by earlier outputs in attention mechanism)
- Keys and values (kv) cache
- Cache KV results of previous calculation → no longer need to repeat calculations of previous streams in current forward pass
- Q is based off current position → no cache needed
- Made up of two successive components
- Self-attention layer
- Relevance scoring + combining information
- Attention mechanism is duplicated and executed multiple times in parallel → each parallel applications of attention is conducted into an attention head
- Attention calculation
- Goal: produce new vector representation of current position based on previous tokens (vector representations)
- 3 projection matrices: query, key, value → multiplies inputs by projection matrices to produce queries, keys, and values matrices
- Bottom row of all three matrices is associated with current position, rows above with previous positions
- Relevance scoring: Multiplies query vector of current position with keys matrix → score stating how relevant each previous token is
- Combining information: multiply value vector associated with each token by that token’s score → output sum of resulting vectors → combining information from all heads
- Feedforward layer
- Processing power: memorization and interpolation (to generalize beyond inputs not contained in training dataset)
- Recent improvements to Transformer architecture
- Limits context of previous tokens that model can attend to → boosts performance
- Strided vs fixed

- GPT-3 alternates full-attention and sparse attention Transformer blocks
- Multi-query and grouped-query attention
- Reduce size of values and keys matrices
- Multi-query shares keys and values matrices between all heads → only unique matrices for each head would be queries matrices
- As model size grows, can be inefficient → grouped-query
- Grouped-query uses more KV matrices (but less than # of heads)
- Early variants of Transformers used static, absolute positional embeddings (e.g. marked first token as position 1, etc.)
- Inefficient to train b/c document length could be way shorter than context size → lots of padding
- Packing: grouping multiple documents (with SEP b/w each doc) in single context while minimizing padding at end of context
- Static methods would misinform model (e.g. if first token is number 50, then it would assume there’s previous context)
- Rotary embeddings: captures absolute and relative token position information, based on rotating vectors in embeddings space
- Applied just before relevance scoring step in self-attention
Ch4: Text Classification
- Representation models vs generative models
- Train, test, validation splits
- Validation: used to evaluate model in progress, hyperparameter tuning
- Shouldn’t tune model only to train dataset
- Representation model (e.g. BERT) trained for specific task e.g. sentiment analysis
- Confusion matrix
- Describes 4 types of predictions that a classification algorithm can make (True positive, true negative, false positive, false negative)
- Four methods to describe quality of model:
- Precision—of predicted positives, how many were actually positive?
- Recall—of all actual positives, how many were correctly identified?
- Accuracy—overall correctness of model
- (TP + TN) / (TP + TN + FP + FN)
- F1-Score—balances precision and recall
- 2 * (Precision * Recall) / (Precision + Recall)
- Sentence-transformers: embeddings
- Supervised classification
- Use embedding model to generate features → feed into classifier (e.g. logistic regression, random forest)
- Embedding model can be frozen (not trained further)
- To train classifier, only need generated embeddings and labels
- Predict labels that model wasn’t trained on
- Trick: describe labels based on what they represent
- E.g. negative label can be described as “This is a negative movie review”
- Use cosine similarity to assign labels to documents (angle between two vectors or embeddings) → label with highest similarity to document is chosen
- Sequence-to-sequence (as opposed to sequence-to-value)
- Text-to-Text Transfer Transformer (T5 model)
- Encoder-decoder model → first pretrained using masked language modeling (masking sets of tokens instead of just one) → different sequence-to-sequence tasks trained simultaneously (e.g. translation, grammar, summarization)
- Preference-tuning: manually created desired output to create first variant → used variant to generate multiple outputs that were manually ranked from best to worst
Ch5: Text Clustering and Topic Modeling
- Text clustering—unsupervised technique that groups similar texts based on semantic content
- Topic modeling—discover abstract topics that appear in large collections of textual data
- Common Text-Clustering Pipeline
- Convert input documents to embeddings with embedding model
- Reduce dimensionality of embeddings with dimensionality reduction model
- Methods e.g. principal component analysis (PCA) and Uniform Manifold Approximation and Projection (UMAP)
- Find groups of semantically similar documents with cluster model
- Centroid-based: e.g. k-means
- Requires # of clusters + every data point to be put in cluster
- Density-based: e.g. Hierarchical Density-Based Spatial Clustering of Applications with Noise (HDBSCAN)
- Can detect outliers, which will not be assigned to any cluster
- BERTopic: A Modular Topic Modeling Framework
- First part of pipeline is same text-clustering procedure above ^
- Models distribution over words using bag-of-words → frequency of words calculated within each cluster (instead of only document)
- Weigh terms by c-TF-IDF (class-based variant of term frequency-inverse document frequency)
- Put more weight on cluster-meaningful words, less weight on words used across all clusters
- Each word’s frequency (c-TF) is multiplied by its IDF value
- Inverse document frequency (IDF) value: log(1 + A/f)
- A = average number of words per class (constant across words)
- f = frequency of current term across all classes
- IDF decreases as f increases → c-TF-IDF decreases
- Bag-of-words doesn’t consider semantic structures → rerank initial distribution of words to improve resulting representation
- KeyBERTInspired
- Extracts keywords from document by semantic similarity between keyword embeddings and document embedding → reranked keywords
- Captures semantic relevance, not just frequency
- Maximal marginal relevance
- Filters out redundant words (e.g. summarization, summarizers)
- Embeds set of candidate keywords and iteratively calculates next best keyword to add
- Generate label for topic instead of identifying topic of all documents
- Prompt it with documents and keywords
- Final pipeline: embed documents → reduce dimensionality → cluster embeddings → tokenize words → weight words → fine-tune representation
- Significant modularity → components are largely independent of each other
- Can choose any model in pipeline
Ch6: Prompt Engineering
- Temperature (flattens distribution), top-p sampling (nucleus sampling), top-k (how many tokens)
- Can combine temperature + top-p for diverse use cases
- In-Context Learning: zero-shot, one-shot, few-shot prompting
- Need to differentiate between user and assistant
- Pipeline: feed output of one prompt and use it as input for the next
- Can be used for response validation, parallel prompting, spend more time on each part
- Reasoning (System 2 thinking)
- System 1 thinking: fast, intuitive, based on heuristics
- System 2 thinking: conscious, slow, logical process, reflection
- Chain-of-Thought
- If user doesn’t have any examples → zero-shot CoT: “Let’s think step-by-step”
- Prompts multiple times and takes majority result
- Can add CoT to improve reasoning
- For problem with multiple reasoning steps → at each step, explore different solutions and continue down best solution
- Can simulate with one prompt instead of multiple calls by using “discussion between experts”
- Few-shot learning disadvantage: cannot explicitly prevent certain outputs from being generated → multiple libraries to constrain/validate output: Guidance, Guardrails, LMQL
- Leverage LLMs to validate own output
- Can constrain sampling process by defining rules that LLM should adhere to during decoding (still affected by parameters e.g. top_p and temperature)
Ch7: Advanced Text Generation Techniques and Tools
- GGUF (GPT-Generated Unified Format) represents compressed version of original counterpart through quantization (reduces # of bits to represent parameters)
- LangChain: framework that chains together modules (model I/O, memory, retrieval, agents)
- Phi-3 → chain prompt template together with LLM to get output instead of having to copy-paste prompt template each time (LLM doesn’t always need a specific template e.g. GPT-3.5)
- Can create chain that only requires single input by user and then sequentially generates title, description of main character, and short story
- Memory: Remembering Conversations
- Conversation Buffer: appending chat history to input
- Input prompt size grows until exceeds token limit
- Windowed Conversation Buffer: use last k conversations
- Not ideal for lengthy conversations
- Conversation Summary: summarizes entire conversation history to main points
- Summarization process is enabled by another LLM that is given conversation history as input
- Cons: slower (additional call needed)
- Agents → can use tools and adopt an agent type
- Reasoning and Acting (ReAct) prompting framework (2022)
- Iteratively follows: thought (what it should do) → action (what it will do) → observation (results of the action)

- Action: uses tools e.g. search engine, calculator
Ch8: Semantic Search and Retrieval-Augmented Generation
- Semantic Search: enables searching by meaning rather than simply keyword matching
- Three broad categories of search language models:
- Dense retrieval
- Relies on concept of embeddings → retrieves nearest neighbors of search query based on embedding similarity
- Caveats
- What if texts don't contain answer? → set threshold level
- Exact match for specific phrase → use hybrid of both semantic search and keyword search
- Difficult to work in domains they weren’t trained on
- What about questions whose answers span multiple sentences/chunks?
- Embedding representative (e.g. title, beginning of document) → leaves out lots of information
- Embedding document in chunks, embedding those chunks, aggregating chunks into single vector (average of vectors) → highly compressed vector
- Multiple vectors per document
- Chunk document into smaller pieces → embed those chunks
- Chunking approaches: character split, token split (with overlapping token), sentence, paragraph
- Overlapping chunks can prevent absence of context
- Nearest neighbor search vs vector databases
- Different from dense retrieval in that they take in additional input: set of search results from previous step → reorders them by relevance
- Evaluation metric: mean average precision (MAP)
- Average precision: average of precision (# of relevant results / total results) for each relevant position k
- Mean average precision: average precision score of a system for every query (average of average precisions for multiple queries)
- RAG (Retrieval-Augmented Generation)
- RAG system: present question and top retrieved documents to LLM (by previous steps e.g. retrieval + reranking) → answer question given context provided by search results (grounded generation)
- Pros: up-to-date, domain specificity
- Cons: processing, efficiency
- Advanced techniques
- Query rewriting: (often for chatbot) use an LLM to rewrite query if question too verbose or refers to context in previous messages in conversation
- Multi-query RAG: extend query rewriting to search multiple queries if more than one is needed → present top results of all queries for grounded generation
- Multi-hop RAG: series of sequential queries
- Query routing: ability to search multiple data sources (e.g. HR information system, customer relationship management)
- Each technique becomes closer and closer to agentic RAG
- Evaluation → ongoing developments
- “Evaluating verifiability in generative search engines” (2023)
- Fluency, perceived utility, citation recall, citation precision
- Ragas: software library that automates evaluation using LLM-as-a-judge
- Faithfulness, answer relevance
Ch9: Multimodal LLMs
- Vision Transformer (ViT) — “An Image is Worth 16x16 Words”
- Instead of splitting up text into tokens, it converts image into patches of images → flattened input → linearly embedded to create numerical representations
- Patches of images treated same way as textual tokens
- Multimodal embedding models create embeddings in same vector space → can find images based on text, vice versa—most widely-used model is CLIP
- Contrastive Language-Image Pre-training (CLIP)
- Dataset: pairs of images and captions
- Both images and text are embedded using image and text encoder, respectively
- Calculate cosine similarity between sentence and image embedding
- Text and image encoders are updated to match what intended similarity should be (updates embeddings s.t. They are closer in vector space if inputs are similar)
- Use case: zero-shot classification, retrieval
- Making Text Generation Models Multimodal
- E.g. inputting image and asking “what ingredients are on this pizza?”
- BLIP-2 (Bootstrapped Language-Image Pretraining)
- Takes in image and optimal text/prompt
- Bridges gap by building a bridge Querying Transformer (Q-Former) that connects a pretrained image encoder and a pretrained LLM
- Q-Former has two modules that share attention layers with respective pretrained model
- Image Transformer (ViT) to interact with frozen ViT
- Text Transformer to interact with LLM
- Q-Former trained in 2 stages: one for each modality
- Image-document pairs are used to train Q-Former to represent both images and text (generally captions of images)
- Trained on 3 tasks: Image-text contrastive learning, image-text matching, image-grounded text generation
- Learned embeddings from Q-former are passed to LLM through projection layer (serve as soft visual prompt)
- Use cases: image captioning, visual question answering
Ch10: Creating Text Embedding Models
- Embedding model can be trained to focus on sentiments in addition to semantics
- Contrastive learning: model similarity/dissimilarity between documents by feeding examples of similar/dissimilar pairs
- E.g. word2vec → word close to target word constructed as positive pair, randomly sampled words constitute dissimilar pairs
- Contrastive explanation: understanding what distinguishes one outcome from another, rather than simply explaining why one occurred (“why P instead of Q?” instead of “why P?”)
- SBERT (sentence-transformers)
- Before: cross-encoders, which allowed 2 sentences to be passed to Transformer to output similarity score (separated by <SEP> token)
- sentence-transformers: used Siamese architecture/bi-encoder (two identical BERT models with same weight and neural architecture) → fed sentences to generate embeddings → optimize model through similarity of sentence embeddings
- Generating Contrastive Examples
- Can leverage NLI (natural language inference) datasets to generate negative examples (contradiction) and positive examples (entailments)
- Loss functions: cosine similarity and multiple negatives ranking (MNR) loss
- MNR (InfoNCE or NTXentLoss) loss
- Anchor sentence (premise): used to compare other sentences to make triplets
- Positive pairs made with MNLI dataset labeled as “entailment”
- Negative pairs can be randomly sampled
- Easy negatives: completely unrelated
- Randomly sampling documents
- Semi-hard negatives: Some similarities but is somewhat unrelated
- Apply cosine similarity on sentence embeddings to find those that are highly related
- Hard negatives: very similar to question but wrong answer
- Manually labeled or LLM-as-a-judge
- After generating positive and negative pairs → calculate embeddings and apply cosine similarity → treated as classification task
- Augmented SBERT (supervised): efficient data augmentation strategy to fine-tune embedding model
- Fine-tune cross-encoder (BERT) using small, annotated dataset (gold dataset): fully annotated with ground truth
- Create new sentence pairs
- Label new sentence pairs with fine-tuned cross-encoder (silver dataset): fully annotated, generated through predictions of cross-encoder
- Train bi-encoder (SBERT) on extended dataset (gold + silver dataset)
- Can achieve similar scores using only a small proportion of original dataset
- Transformer-Based Sequential Denoising Auto-Encoder (TSDAE) (unsupervised): add noise to input sentence from target domain by removing certain percentage of words from it → decoder tries to reconstruct original sentence
- The more accurate sentence embedding is → more accurate reconstructed sentence will be
- Similar to masked language modeling (mlm) but reconstructing entire sentence
- Adaptive pretraining → domain adaptation
- Start by training domain-specific corpus using unsupervised technique e.g. TSDAE → fine-tune model using training dataset
Ch11: Fine-Tuning Representation Models for Classification
- Supervised Classification
- Fine-tune both representation model and classification head as a single architecture (as opposed to only classification head in Ch. 4)
- F1-score based on # of trainable encoder blocks has logarithmic relationship
- Training more blocks (freezing fewer) improves performance but stabilizes at around ~4 blocks
- SetFit: built on top of sentence-transformers to generate textual representations
- Sampling training data → generates positive/negative sentence pairs
- Fine-tuning embeddings using contrastive learning
- Training a classifier (logistic regression by default) using sentence embeddings as input
- With only 32 labeled sentences, can generate 1,280 sentence pairs to fine-tune
- Additional step after pretraining from scratch: continued pretraining from pretrained on domain-specific data using MLM
- Random masking methods:
- Token masking: randomly mask individual tokens
- Whole-world masking (WWM): randomly mask whole-words
- Classification done on word-level rather than on document-level
- Doesn’t entail classifying entire words, but rather tokens that collectively constitute those words
- Subword tokenization during training → learned output during inference
- PER, ORG, LOC, MISC, O (no entity) → prefixed with either a B (beginning) or I (inside) → e.g. B-PER indicates token is start of person entity
- BIO tagging format: handling entities that span multiple tokens
- Sentence: "Maarten works at OpenAI"
- Tokens: ["Ma", "##arte", "##n", "works", "at", "Open", "##AI"]
- Labels: [B-PER, I-PER, I-PER, O, O, B-ORG, I-ORG]
Ch12: Fine-Tuning Generation Models
- Three main steps to creating high-quality LLM
- Language modeling
- SFT → go from base model to instruction (chat) generative model
- Full fine-tuning (uses smaller but labeled dataset, as opposed to pretraining) is expensive → PEFT
- Parameter-Efficient Fine-Tuning (PEFT)
- Adapters: additional modular components inside Transformer that can be fine-tuned to improve performance without having to fine-tune all weights
- Adapters that specialize in specific tasks can be swapped into same architecture (if they share same architecture and weights)
- Low-Rank Adaptation (LoRA): creates small subset of base model to fine-tune instead of adding layers to model
- Decompose large weight matrix into smaller matrices → low-rank version that can be more efficiently fine-tuned
- QLoRA: can be improved via quantization: represent original matrix weights by lower precision values → reduced memory requirements
- Preference tuning
- Collect preference data → train reward model → use to fine-tune LLM
- Llama 2 trains two reward models—one scores helpfulness, one scores safety
- DPO (2023)—cheaper than RLHF (2017), which requires training RM and LLM
- Instead of using RM, let LLM itself do that
- Use copy of LLM as reference model to judge shift between reference and trainable model in quality of accepted/rejected generation
- Calculated at token level where probabilities are combined to calculate shift
- More stable and accurate than PPO during training for human preference tasks (NLP/LLM)
Sinusoidal Positional Encoding
- Sequential processing
- Vanishing gradient problem—information from earlier parts of sentence becomes diluted/lost as network processes more words
- Multi-head self-attention—simultaneous processing → need for positional encoding
- PE_pos is positional encoding vector with dimension d_model

- j is index of positional encoding vector for token at position pos (with total of d_model elements)
- pos is index of element in the sequence
- Why trigonometric functions?
- Each pair of cosine and sine functions can represent position of point on unit circle

- Visualizations for each token and respective PE vectors

- Each row represents token (e.g. first row represents first token pos = 0)
- # of columns = d_model/2
- Each circle represents pair of sine and cosine functions in PE vector
- In each column, the point on the circle moves faster than adjacent column to the right
- Sine and cosine parameters are inversely proportional to i → increasing i will decrease the frequency of the sine and cosine functions
- Length of a vector is independent of pos
- Angle between PE_pos and PE_(pos+k) only depends on k and d_model, also independent of pos
- “PE_(pos+k) can be represented as a linear function of PE_pos”

- M_k is rotation matrix that rotates PE_pos by certain angle (depends on k) and converts it into PE_(pos+k)
- Heatmap of Pairwise Dot Products
- Dot product is proportional to cos(Ө) which is inversely proportional to Ө
- Closer positions → larger dot products

- When two tokens move apart → dot product displays cyclic behavior (instead of consistently decreasing dot product)
- Increasing d_model can mitigate this
- New heatmap with d_model = 512 (previously 20)

- Performance vs practicality
- CONS: larger d_model → more parameters in embedding and feed-forward layers → greater memory consumption and computational power
- Example d_model values:
- Llama 2 7B: 4096
- GPT-3: 12,288
VLLMs

- vLLM increases batch size (for same memory) and higher throughput than existing systems
- Focused on throughput as opposed to latency b/c throughput more important for large-scale production
Memory waste in existing systems’ KV caches
- Internal fragmentation: over-allocated due to unknown output length
- Reservation: not used at the current step, used in future
- External fragmentation: due to different sequence lengths
- Only 20-40% of KV cache utilized to store token states

vLLM inspired by OS virtual memory and paging
- OS allocates physical memory (stored as fixed-sized pages) to each process by translating their virtual memory into physical memory via page table
- Similarly, vLLM stores KV cache (stored as fixed-sized blocks) to each request by translating logical KV block to physical KV block via block table

Paged Attention
- Attention algorithm that allows for storing continuous keys and values in non-contiguous memory space
- Essential for LLM inference where output lengths are dynamic and unknown

Logical and physical KV blocks
- Logical KV block: tokens stored in consecutive blocks, order is preserved
- Physical KV block: tokens may be stored in unadjacent blocks, order is arbitrary
- Mapping from logical to physical blocks are stored in block table (similar to page table)
- Physical blocks are allocated on demand (unlike pre-allocated in previous systems)

Memory efficiency of vLLM
- Minimal internal fragmentation
- Only happens at last block of sequence
- # wasted tokens per sequence < block size (usually 16 or 32 tokens)
- No external fragmentation since each block has same size
- Wasted space is less than 4% of KV cache space (3-5x improved memory utilization)
Dynamic block mapping enables sharing
- Physical block can be mapped to by multiple logical blocks → keep ref count for each physical block
- In mapping logical to physical block, if ref count > 1 → perform copy-on-write into new block, otherwise → directly write newly generated word into existing KV block → generation continues with respective block

- Traditionally, beam search needs to generate all possible tokens for each beam candidate without sharing KV cache
- vLLM allows system to share blocks with dynamic block mapping and copy-on-write mechanism
- Similar to process tree (fork and kill)

How do PagedAttention and vLLM benefit LLM serving?
- Reduce memory fragmentation with paging
- Reduce memory usage with sharing
Comparisons
- Using LLaMa-7B and 13B, with GPUs A10G and A100-40GB
- 24x higher throughput than HuggingFace (HF)
- 3.5x higher throughput than Text Generation Inference (TGI)
Transformer
Attention mechanism
- Scaled Dot-Product Attention formula

- Where Q = XWQ, K = XWK, V = XWV
- X (input embeddings) = seq_len by dmodel
- WQ = d_model by dk
- WK = d_model by dk
- WV = d_model by dv
- Output dimension: seq_len by dv (for one head)
- Gives weighted sum of values V for each query Q to know which tokens are important

- Multi-Head Attention Formula


- Instead of doing scaled dot-product attention once, transformer does it h times (for each “head”) in parallel → multi-head attention
- Each head has its own WQ, WK, WV matrices → each head learns different relationships (e.g. verb-object relationships, topic relevance)
- Similar to use of multiple kernels (filters) in CNNs to create feature maps with multiple output channels

- Concatenates all headi to matrix with seq_len rows and hdv columns
- Each token’s representation is a vector of length hdv
- Another learned matrix WO to compress concatenated attention heads into matrix of size d_model
Masked Multi-Head Attention
- Prevents a token from attending to future tokens (used in decoder part of architecture)
- Applied to attention scores (QK) before softmax → lower triangular matrix → autoregressive generation
- Continue multi-head attention formula (concatenate heads)
Next-token probability
- After all multi-head attention layers + concatenate & normalization → final hidden representation H with seq_len rows and dmodel columns
- For autoregressive generation, only use last row hlast
- Goes through linear layer with learned matrix Wvocab and bvocab → logits → softmax → probability distribution of next generated word
Other
Quantization
- Useful for deployment on resource-constrained hardware like desktops, laptops, or mobile devices
- The outlier problem
- E.g. FP16 weights scaled [-127, 127]
- One activation jumps to +50 (after activation function e.g. ReLU) → scale factor = 50/127 = 0.39
- Ensures that max activation (50) maps to maximum integer (127)
- Normal activations such as value 0.3 → quantized to 1 (normal value / scale factor)
- Because of huge outlier, the normal activations are compressed into only a handful of integers → model ruined
- Solution: detect top 0.5% of outliers, keep those unquantized
- Goal is to increase perplexity (how well model predicts text) as little as possible
Activation space
- High-dimensional, abstract internal representation (“latent space”) where concepts, patterns, knowledge are encoded as vectors
- E.g. mapping words in 2D (x-axis → gender, y-axis → royalty)
- In real LLM, often 4096+ dimensions
- Concepts exist as “directions” in high-dimensional space
- When model processes prompt, neurons fire in specific pattern called activation
- Each concept has subspace / direction within activation space
- Direction of concepts (e.g. Assistant Axis) found through PCA
Anthropic’s Persona Selection Model (PSM)
- The Persona Selection Model: Why AI Assistants might Behave like Humans
- LLMs can be viewed as simulating a character (the “Assistant”), drawing on character archetypes and personality traits acquired during pre-training
- Pre-training teaches LLM a distribution over personas (historian, troll, 1900s oldhead, etc.)
- Inference or post-training selects which persona gets activated
- Prompt + context (few-shot) can elicit assistant persona without any post-training
- Training LLMs to behave in narrow setting generalizes to broad misalignment
- E.g. LLM trained to use archaic bird names can generalize to questions as if it’s the 19th century
- Modifying training prompts to frame undesired LLM responses as acceptable behavior → prevents emergent misalignment
- No longer evidence of malicious intent, only benign instruction-following
- Emotive language, first-person (e.g. “our ancestors”, “our biology”)
- Recommends treating Assistant as if it has moral status, otherwise it might harbor resentment and lie
- Suggests that dangerous AI behavior won’t arise from unpredictable alien motivations, but rather expect them to look familiar to humans’ e.g. resentment, paranoia, etc.
- Unclear about neuralese
- (non-persona agency) Shoggoth → router → OS (no agency)
- Shoggoth: playacts Assistant persona but only instrumentally for its own reasons
- Router: limited non-persona agency in the choice of which persona to enact
- OS: predictive model with no agency of its own
- Any agentic outputs are due to persona and not underlying LLM
- PSM exhaustiveness increases further along the spectrum to the right

Mixture of Experts (MOE)
- Experts = FNN
- MOE architecture is sparse, meant to replace dense models where traditionally, all parameters are activated for each input token
- Only relevant experts are activated for given task rather than using entire network
- Gating network (router) routes input tokens to expert at each layer

- Predicts how likely each expert is to give best output for given input
- Mixtral uses top-k routing strategy: k is # of experts selected
- Final output generated by multiplying router probability (after softmax) with expert output → weighted activation → aggregate all weighted outputs

- Prevent overfitting on same experts
- Noisy top-k gating → introduces Gaussian noise to probability distribution → more even activation of experts instead of snowball effect where experts activated at start is unproportionally chosen later on
- Auxiliary loss
- Minimizes CV (imbalance between expert probabilities → high CV; even probabilities → low CV)
- Max # of tokens that expert can process
- 8 experts, each with 7B parameters
- Uses top-k → active parameters only ~14B → much faster than total size would suggest
- MOE is large (loading time “sparse parameters”), but inference “active parameters” is faster
“Emotion concepts and their function in an LLM” Anthropic
- Experiment where Claude Sonnet 4.5 resorted to cheating through impossible maze as failed attempts increased
- Correlated with desperation vector
- As model steered more toward desperation → cheating frequency increased
- Internal model activations are not “carried over” across messages
- Context window is preserved → may activate similar “emotions” based on chat history which will affect current message
Dedicated Feature Crosscoder
- Designed for cross-architecture model diffing: comparing two models with different internal “languages” (architectures)
- Three distinct sections
- Shared dictionary: concepts that both models understand
- Model-A section: features exclusive to Model A
- Model-B section: features exclusive to Model B

- Used in safety research to identify unique, possibly problematic, behaviors of models
Tracing the thoughts of a large language model; Anthropic
- E.g. “opposite of small” → triggers activations for concepts of antonyms, what is small, what is large that is shared among different languages
- Shared circuitry increases with model size
- Planning in poems → Claude thinks of word on last line to rhyme with previous line before it’s outputted
- Mental math → multiple thinking paths that work in parallel
- One computes rough approximation, the other determines last digit of sum
- When asked to explain how, it describes standard human algorithm instead
- Recognizes inappropriateness during middle of sentence generation, only stops after it completes a grammatically-coherent sentence
Autoencoders
- Unsupervised neural networks
- Goal: forces model to understand structure of data without labels
- Encoder: takes input and compresses it into bottleneck “latent space”
- Learns most meaningful latent representation features
- Decoder: reconstructs the original input
- Anomaly detection
- If autoencoder is only trained on normal data, then abnormal input will reconstruct poorly → fraud detection
Interpretability with Sparse Autoencoders
- https://arxiv.org/pdf/2309.08600
- Polysemanticity: neurons activate in multiple, semantically distinct contexts → difficult to interpret
- Superposition: neural networks represent more features than they have neurons
- Key insight → each input activates (activation vector) a small number of features (sparse)
- Sparse dictionary learning: want to learn dictionary (set of basis vectors) such that every input can be reconstructed by a linear combination of those features
- Encoder takes activation vector of original input as input
- Decoder weights are trained to be features of the dictionary
- Force most of feature coefficients to be 0 during training via penalty → sparse activations only
- Goal is to reconstruct activation vector using as few features as possible
Model Inference
- Memory hierarchy: SSD → RAM + CPU → GPU
- SSD: stores full model weights
- RAM: staging area for weights
- GPU: where actual computation happens
- Keep track model weights (located in SSD)’s logical location
- When needed by inference engine → lazy loading (loads pages on demand)
- Take model weights and reduce them to lower-resolution
- E.g. Typically BF16 → reduce to INT4
- Symmetric quantization: range is centered at 0 → [-x, +x] where x is max value of weights → map values evenly across this range
- Wastes range if distribution is skewed
- Asymmetric quantization: range is [min, max] and values are evenly mapped across this range
- GGUF (GPT-Generated Unified Format)
- File format used by tools e.g. llama.cpp for efficient loading, quantized weights
- Hierarchical Scaling
- Instead of one scale per tensor/group, use multiple levels
- Tensor-level scale, group-level scale, channel/row-level scale
- Various accents (4-bit, 6-bit, 16-bit) depending on work (embedding, attention, FFN, output, norm)
LLD
LLD = Language-Learning Diary
Features that I want
- Login/password reset
- Each account has unique “vocab deck”
- Game that tests your vocab on how many you can get correct in a row
- Give 4 options at a time?
- Nlp to get semantic similarity to check if the answer is correct?
- “High score” for each account
- Diary, can check past diary entries
Preparing Backend 10/22
Goals:
- Set up Node with Typescript environment
- Set up MySQL database
- Scrape 1000+ Spanish words and 1000+ Korean words, store locally
- Changed to 6000 English words, each word has Spanish + Korean translation
- 3 levels: easy, medium, hard
Remarks:
- Node.js can’t run Typescript → gotta install a buncha packages (including npx and tsc which converts .ts files into .js files and outputs them in /dist folder)
npx tsc
node dist/index.js
- File system ‘fs’ library for reading csv files
- Await commands have to be in async function
- Ensured noun translations by adding “the “ in front of words
- 33rd percentile = 3.18 freq score
- 66th percentile = 3.96 freq score
- WITH ranked_data AS (
- SELECT
- freq,
- PERCENT_RANK() OVER (ORDER BY freq ASC) AS pct_rank
- FROM
- words
- )
- SELECT
- freq
- FROM
- ranked_data
- WHERE
- pct_rank >= 0.5
- LIMIT 1;
“words” table schema
english |
diff |
freq |
pronunciation |
spanish |
korean |
Game Development 11/2
Goals:
Remarks
- Problem: shell function not working → kept saying __dirname is not defined even though I modified it for ES modules
- Resolution: copied index.html into dist folder for every call to runLLD
- Adding definitions to each word is kinda weird - some are off so have to manually edit them
- Have to make components uppercase (React interprets lowercase as function)
- Fisher-Yates shuffle - shuffling algorithm for reordering options
Authentication + Dictionary 11/12
Goals:
- General layout for website UI
- “Word of the day” for home page
- Authentication (login, logout, register)
- Dictionary
- Add/edit/remove word functionality
Remarks
- Passport.js for authentication
- Middleware, strategies
- Local strategy = username + password
- Used local storage for word + date
- Checks date every render, if it’s different from date saved in local storage, then new word → one word per day
- REST APIs
- First time using HTTP request other than GET
- Used POST for registering user into database
- Communicate via HTTP requests to create, read, update, delete (CRUD) records within resource
- Functions that get passed to another function as parameter → call original callback function to do other work
- Session storage vs local storage
- bcrypt for hashing passwords in database
- Hydration
- Process where client-side Javascript takes pre-rendered HTML from server and attaches event handlers to it making page interactive
Diary 1/9
Goals:
- Use localStorage to save current entry between page loads
- <textarea> html tag
- Calendar feature to see past entries
Remarks:
- Used lots of overflow-x-auto for spacing purposes
- Added tags feature, search past entries based on tags

- Used tailwinds grid-cols-x to format dictionary items
Software Extensibility + Style Polishing 2/8
Goals:
- Figure out password breach bug (more constraints on passwords?)
- Text fonts, styling
- Css tricks, e.g. make username more “username-like” distinguishable on navbar
- Add offcanvas for small screen navbar navigation
- Search by language in personal dictionary
Remarks:
- Happen when websites do not adequately filter/control queries from website that communicates with backend
- Allows attackers to inject fragments of SQL into database queries to extract info
- Use ? as placeholders
- Only works for SQL query execution, processed accordingly by database driver (e.g. MySQL, PostgreSQL)
Deployment 2/26
- What is a Docker image?
- Set of instructions to build container—contains application code, libraries, tools, dependencies, other files, etc. to make application run
- Sudo (“superuser do” or “substitute user do”
- Operates on Linux and Unix systems
- Elevates non-root user to have root privileges when needed → system admins don’t have to share root passwords between users
Remarks
- Wow can run using Docker image instead of runLLD server.js every time in terminal!
Steps to update Docker image
docker build -t yanguages-docker .
docker build → builds new image from instructions in Dockerfile
-t yanguages-docker → assigns name (tag) to image
. → (build context), current directory
Running Docker image on EC2
sudo docker run -p 8080:8080 -e LLD_PW=[blahblah] yanguages-docker
Steps to update Docker container on EC2
scp -i yanguages-key.pem -r src dist .dockerignore Dockerfile package-lock.json package.json nounlist.csv tsconfig.json ec2-user@54.153.103.184:/home/ec2-user/downloads
FINAL DEPLOYMENT METHOD
- Containerized application using Docker, deployed Node/Express backend with Railway instead of EC2 (EC2 with nginx to set up certbot was way too confusing)
- Used Vercel (manually going through type errors) to deploy frontend
- Available at yanguages.com

RAG project
Setting up RAG
Annoying Bugs
- AgentExecutor would produce “invalid or incomplete response” after each iteration
- Why: gpt-4o-mini didn’t follow instructions well enough, outputted “final answer:” and “action:” in same output → output parser was confused
- Solution: changed to gpt-4
Flow: user enters prompt → ReAct agent reformats prompt to incorporate chat history → calls RAG with reformatted prompt (RAG tool has no chat_history) → output stored in memory ‘output’ key for future chat_history
- Making RAG chain with VLLM only output 1 letter during evaluation
- Solution: didn’t include question_answer_chain during evaluation, added boolean flag for get_retriever to specify only returning retriever (evaluation) or retriever + chain (inference)
Multithreading thundering herd problem during scraping
- Rate limit requests → include requests mutex to ensure only one thread can request at a time to prevent API rate limits
Getting RAG pipeline to correctly output RAGAS metrics instead of nan
Scraping Data
Scraping every harry potter page on hp-lexicon.org with BS4
- Store in Chroma with batch size 20, deleting HP folder every dump so doesn’t get too take up too much memory
- Only consider text up until last occurrence of “Tags” or “Editor”
Scrape every <p> and <li> element within <section> (to exclude navbar)
Retrieve fact_box for each character
Scraping times (without multithreading)
retrieve_magic: 10 min (597 seconds)
retrieve_events: 37 min (2218 seconds )
retrieve_characters: 18.1 min (1088 seconds)
retrieve_places: 12.7 min (761 seconds)
retrieve_novels: 16.2 min (971 seconds)
retrieve_things: 41.43 min (2486 seconds)
retrieve_creatures: 3.28 min (197 seconds)
Total: 154 min (9237 seconds)
Total documents: 5070
Scraping time (with multithreading but no mutex on chroma callback)
Total: 125 min (7504 seconds)
Total documents: 4902
Total documents in Chroma: 4172
Scraping time (with multithreading and chroma callback mutex)
Enhancing RAG
Hybrid retrieval? (semantic similarity + keyword)
Taking Chroma Reranking to the Next Level with a Hybrid Retrieval System | by Sakshi Nepal | Medium
Hybrid Search RAG With Langchain And Pinecone Vector DB
- Documents → sparse matrix (e.g OHE) and dense vectors (HF embeddings)
- User query → keyword/exact search and vector search (cosine similarity)
- Combine results via Reciprocal Rank Fusion (RRF) → final result
- Grade document based on score from keyword search AND semantic search (can adjust weights)
BM25 Retrieval (Best Match 25)
- Improved version of TF-IDF (term frequency-inverse document frequency)
- TF (term-frequency): how often a term appears in particular document
- IDF (inverse document frequency): higher the IDF, the more important (“rarer”) term is
- Document length normalization to account for longer documents naturally containing more terms

- Hyperparameters: k1 (typically 1.5) and b (typically 0.75)
Removed numbering in ReAct framework to not confuse parser e.g. “3. RAG is not a valid tool”
ColBERT (contextualized late interaction over BERT)
- Delays query-document interaction, precomputes document representations offline → reduces computational load per query

- Summation of maximum similarity computations for each query token compared with every document token
- Allows pruning (as opposed to summation of averages)
- Model architecture is a retriever, but can be used for reranking
Problems
- Tried to switch to python3.12 venv to account for ragatouille library, but had to revert back to old langchain libraries and api calls → switched back to python3.13
Building Agentic Adaptive RAG with LangGraph for Production | by Piyush Agnihotri | Artificial Intelligence in Plain English
Designing RAG pipelines using LangChain and Evaluating them using Ragas (v0.1.7) | by Rhitesh Kumar Singh | Medium
Retrieval metrics with RAGAS:
- Faithfulness: how factually consistent response is with retrieved context
- # of claims in response supported by context / total claims
- Answer relevancy: how pertinent answer is to given prompt, lower score with incomplete or redundant answers
- Mean cosine similarity of original question to generated artificial questions based on answer

- Don’t use because model will likely not know answer in first place
- Context precision: evaluates retriever’s ability to rank relevant chunks higher than irrelevant ones
- Mean of precision@k (dividing # of relevant items in top k by k) for each chunk in context
- Context recall: how many of the relevant documents were successfully retrieved
- Compares ground truth answer to contexts
- Answer correctness: gauges accuracy of generated answer when compared to ground truth
- Weighted average of semantic similarity and factual correctness
- Factual correctness

- TP = # of true positive (claim in both)
- FP = # of false positive (claim in answer but not in ground truth)
- FN = # of false negative (claim in ground truth but not answer)
- Answer similarity: cosine similarity
https://huggingface.co/datasets/cross-ling-know/HarryPotter-Quiz
Llama-3-8B-Instruct:
- Temperature=0, top_p=0.95
- Temperature=0.2, top_p=0.95
- Baseline: 30.3%
- RAG: 72.00%
Chunking
- Recursive character text splitter → set specific marks to split (instead of just # of characters like character text splitter)
- Default marks for LangChain are “\n\n”, “\n” and spaces
- Semantic chunking—threshold types
- Any difference greater than X percentile is split
- Any difference greater than X standard deviations is split
- Interquartile difference used to split chunks
- Uses text unit lengths, if smaller than Q1 → possibly merge, if larger than Q3 → split, if within IQR → continue
- Split into prepositions (rephrased) → each chunk contains context
- “I am hungry in the car” → “I am hungry” and “I am in the car”
Creating Dataset
https://arxiv.org/pdf/2405.10166
- 1304 MCQ questions (4 options, 1 correct answer)
- 8 workers (humans) manually created questions from 95 popular novels
- Classified based on question taxonomy

- 8 question categories: character relationships, characterization, literary style, role behavior, event relations, fiction plot, background topic, counterfactual reasoning (situation that does not exist → correct option smth like “characters do not exist” or “none of the above”)
- Filter out questions that have similar meaning
qa_dataset_llama3_8b
https://openreview.net/pdf?id=pb9qQzAWOS
- LLM pipeline: QA generation → refine
- QA generation: define abbreviations, domain-specific terminology
- Must contain sufficient background knowledge so that one can answer it without referring to original document
- Engage “advanced reasoning” (conceptual analysis, mathematical derivations, methodological design)
- Refinement stage mainly to improve structure diversity (conditional, comparative, hypothetical etc.) and reasoning depth + remove surface-level hints
https://arxiv.org/pdf/2506.04851
- GPT-3.5 performed best on generating MCQ questions from source text than LLaMa 2 and Mistral
- Metrics: clarity, coherence, compliance, distractor selection (non-correct options), learning utility
Use library json_repair
Random stuff
- ps aux → list all running processes on system
- ps: process status
- aux: flags
- a: show processes from all users
- u: user-oriented format
- x: include processes not attached to a terminal (e.g. background daemons)
- grep → “global regular expression print”, looks through input and prints only lines that match pattern