Explainable Reasoning

A hospital model can score a patient well and still say nothing a doctor can check. xHAIM summarises each chart, lifts pneumonia AUC from 76.3 to 96.7, and cites the notes behind each answer.

Pick a task, then pick a method. Watch the score bar and the read-out change. Then we build the pipeline piece by piece: the baseline, the zero-shot language model, the five parts of xHAIM, and the way to grade an explanation.

You need a rough idea of what a classifier is (a program that answers yes or no) and what a language model does. We build the rest from zero.

Based on Lecture 9.2 (April 2, 2026) of MIT MMAI, Multimodal AI (Spring 2026), from the MIT Multisensory Intelligence group led by Paul Liang. The lecture presents the xHAIM paper by Periklis Petridis, Georgios Margaritis, Vasiliki Stoumpou and Dimitris Bertsimas. Lecture slides · The paper. Every idea is re-taught here in our own words and devices.

Score the methods

The scores are the lecture’s (slide 16, ROC AUC in percent, on MIMIC-IV ICU patients). A score of 50 is a coin flip. The “explains itself” line comes from slides 3 to 14: HAIM gives no explanation, the zero-shot model gives one that nothing checks, xHAIM gives one that cites the patient’s own notes.

Chapter 0

A Chart Nobody Can Read in Time

See why a hospital model needs two things at once: a better answer, and a reason a doctor can check

It is three in the morning in an intensive care unit. A nurse asks the doctor on call one question: will this patient be alive in 48 hours? The answer sits somewhere in the patient’s file, and the file is huge.

The file holds four kinds of record. Each kind is a modality, a different form of data, the way a photo and a voice memo are different forms. A task that uses several modalities together is multimodal. Here is what this patient’s file holds, using the lecture’s own list.

  1. Tabular data. Rows and columns, like age, sex and the medicines the patient takes. This kind of data is tabular.
  2. Time series. Numbers measured again and again, like blood pressure every hour. A list of values in time order is a time series.
  3. Images. Pictures, like a chest X-ray.
  4. Notes. Free text that people wrote: radiology reports and the patient’s past medical history.

The lecture asks one question about this pile: can a program use all of it to predict a diagnosis or an outcome? A prediction task is one fixed question with a yes or no answer. The slide sorts the tasks into two groups. Pathology tasks ask what the patient has now: pneumonia, diabetes. Outcome tasks ask what will happen next: mortality, length of stay.

A program that answers such a question is a classifier. It reads the data and says yes or no, usually with a probability. Researchers already built classifiers for this job. This lesson follows one new method, xHAIM, from the lecture’s deck, which comes from a paper by Periklis Petridis, Georgios Margaritis, Vasiliki Stoumpou and Dimitris Bertsimas. The lecture’s opening slide also points to a longer article on human-centered explainable AI at The Gradient.

Two goals that pull apart

The method has two goals, and the lecture names both in its title. The first is performance: a better score on the prediction. The second is explainability: the program must give a reason that a person can check.

Why does the second goal matter? Picture a model that says “96% chance of pneumonia” and nothing else. A doctor cannot tell whether the model read the X-ray, read a note, or found a pattern that only looks real. A model whose inner workings are hidden like this is a black box. The lecture says a black box makes clinical adoption harder, and Chapter 1 returns to that point.

Feel the first problem

The first obstacle is size. A real patient file holds far more than one question needs. For “does this patient have hypertension?”, most of the file does not matter. A few lines about blood pressure matter a great deal. The reader must find those lines.

The device below makes this concrete. It shows a toy chart of 240 items, 60 for each modality. Twelve of them matter for the question. You do not know which. Drag the slider to read more items, and compare two reading orders: from the top of the chart, or the most relevant first.

Read the chart

Each square is one item in the patient’s chart. Squares fill in as you read them. Green squares are the twelve items that answer the question. Drag the slider, then switch the reading order.

60

Illustrative toy: 240 items, 12 of them relevant, placed by a fixed seed so the picture is the same on every visit. The numbers are not from the lecture. The point is only the shape: reading in chart order finds relevant items slowly and at random, while a ranked order finds all twelve in the first twelve reads.

In chart order you find relevant items only by luck. In ranked order every read counts until all twelve are found, and then you can stop. A program faces the same choice. It can swallow everything, or it can first find the part that matters. The method in this lesson does the second thing, and Chapter 4 shows how.

Notice also what the ranked order needs: a way to say, for each item, how much it matters to the question. The lecture calls the question a task sentence, a short list of words about the target, such as “essential hypertension, high blood pressure, systolic, diastolic”. Everything else follows from it.

The road

The lecture is twenty slides and tells one story: an old approach, its weak spots, a new approach in parts, and its results. This lesson follows the slides in order.

  1. The HAIM baseline: turn every modality into numbers and glue them together.
  2. The zero-shot language model: turn everything into text and ask.
  3. The xHAIM plan: five steps, and how a table row becomes a sentence.
  4. Finding the relevant data: a task sentence, chunks and two kinds of similarity.
  5. Writing one summary: a short paragraph for each modality.
  6. Finetuning and the final classifier: encoders tuned to this data, then a prediction.
  7. Grounded explanations: a reason with citations to the raw notes.
  8. The prediction results: what AUC measures and what the numbers say.
  9. Grading explanations: a rubric, human graders and a language-model judge.
  10. The field guide: numbers, a checklist, the core code and where to go next.
In the toy chart, why does reading in ranked order find all twelve relevant items so much sooner than reading in chart order?

Chapter 1

The Baseline: Turn Everything Into Numbers and Glue Them

Follow one patient through HAIM, the method xHAIM improves, and find the two places where it hurts

A data scientist at a hospital faces the file from Chapter 0. Her classifier only understands numbers. A chest X-ray is not a number. A radiology note is not a number. She needs a way to turn each kind of record into numbers, and she needs it to keep what matters.

The standard answer is an embedding: a fixed-length list of numbers that stands for a record. Two similar records get two similar lists. Think of an embedding as a name tag made of numbers. The tag is short, and a program can compare tags quickly.

The HAIM recipe

The earlier method is HAIM, short for Holistic AI in Medicine. It comes from Soenksen and colleagues (npj Digital Medicine, 2022), and slide 3 draws it as a pipeline. It has four moves.

  1. Take in every modality. The patient’s tabular data, time series, images and notes all go in.
  2. Embed each one. A separate model for each modality turns its records into an embedding. These are the modality-specific models. The slide labels the four outputs Etabular, Etime series, Eimages and Enotes.
  3. Concatenate. Place the four lists end to end to make one long list. Joining modalities this way is fusion.
  4. Classify. Feed the long list to a final classification model. Train it for any task: does the patient have pneumonia or not?

Slide 11 names two of the encoders in the original pipeline: DenseNet for images and ClinicalBERT for notes. Both were pretrained, meaning someone trained them earlier on a large body of data that is not this hospital’s data.

The data flow, with shapes

Let us make the flow exact. Suppose each encoder returns a list of 768 numbers. That size is only an example; the slides do not give sizes, and real encoders differ. Four lists of 768 numbers, joined end to end, give one list of 3,072 numbers. The classifier reads those 3,072 numbers and returns one probability.

# HAIM in six lines (shapes are illustrative)
mods = ["tabular", "timeseries", "image", "notes"]
e = [encoder[m](patient[m]) for m in mods]   # 4 vectors, each (768,)
x = np.concatenate(e)                                # one vector, (3072,)
p = classifier.predict_proba(x[None])[0, 1]    # one number between 0 and 1

Nothing here looks wrong, and in many ways it works. One flow serves every task. Only the last model changes: swap the label from pneumonia to mortality and train again. The lecture also lists what is wrong, on slide 4, in two parts.

Problem one: too much input, so noisy input

The first problem is size. The slide puts it plainly: there is too much input data, and much of it is irrelevant to the final task. Think of the 240-item chart again. The encoders must describe all of it.

The second half of the sentence matters more. Each embedding has a fixed length. So a single embedding has to capture every detail of every note. When the notes hold thousands of words and only a few lines matter, the lines that matter get a tiny share of the numbers. The classifier then sees a faint signal under a lot of noise.

Try it with a toy. The device below shows one fixed-length vector. It gives every fact in a chart an equal share of the slots. That is a simplification, because real encoders do not split evenly, but it shows why more input does not mean more signal. Four of the facts are relevant.

Squeeze a chart into a vector

The bar is a 16-slot vector. Green is the part that carries the four relevant facts. Drag the number of facts in the chart, then switch to selecting the most relevant facts first.

40

Illustrative toy, not the lecture’s numbers: 16 slots, 4 relevant facts, and every fact that gets in receives an equal share. The only claim from the lecture is the direction: more irrelevant input means a noisier vector, because one embedding must capture all the detail.

With 40 facts squeezed in, the four that matter own about one slot and a half. With only the eight most relevant kept, they own half the vector. Selecting first is a cheap way to turn noise into signal, and it is the first idea xHAIM adds.

Problem two: a black box

The second problem on slide 4 is the one Chapter 0 raised. The classifier takes 3,072 numbers and returns 0.97. Nothing in those numbers says which note, which image or which lab value drove the answer. The lecture calls this a black box architecture and says it makes adoption and clinical deployment harder.

The failure shows up in three steps. The symptom: a doctor sees “97% pneumonia” for a patient who looks well, and asks why. The measurement: you cannot answer, because the answer is spread across the 3,072 numbers. The fix is not a better classifier. The fix is to change what the classifier reads, so that the reason exists in words before the prediction is made. Chapters 3 to 7 build that change.

Why does adding more irrelevant facts to a patient’s notes make the HAIM embedding worse for a specific task?

Chapter 2

The Other Baseline: Write It All Down and Ask a Language Model

Try the opposite of HAIM, hand a model the whole chart as text, and find out what it cannot do

A second data scientist hears the problem and shrugs. “Skip the embeddings. A language model reads text. Turn every record into text and ask it.” This is the lecture’s second existing approach, on slide 5, and it sounds almost too easy.

A language model (LLM, for large language model) is a program that reads text and writes text. You give it a prompt, which is the text it must continue or answer. It gives back a response. A model used with no examples and no extra training on your data is used zero-shot. “Zero shot” means zero training examples shown for this task.

The recipe, as a real request

The slide gives three moves. Convert every data source to text. Hand the raw information to an LLM. Ask for a prediction and an explanation. Here is what the request and the reply look like. The wording is ours; the lecture does not print a prompt.

# prompt, built from the whole chart (illustrative wording)
prompt = f"""Patient record:
{tabular_text}
{timeseries_text}
{image_reports_text}
{all_notes_text}

Question: Does this patient have pleural effusion?
Reply with a probability from 0 to 1, then an explanation."""

reply = llm(prompt)
# reply ~ "0.85. The notes describe a small left pleural effusion..."

The reply is a string. A program must read a number out of it. The explanation arrives for free, because the model writes it in the same breath. That is the appeal: one call gives a prediction and a reason. Now the lecture’s three complaints, from slide 6.

Complaint one: too much input

A language model reads a limited amount of text at once. The unit is the token, a small piece of text, roughly three quarters of an English word. The limit is the context window. If the prompt is longer than the window, something must be cut, and a cut may remove the one note that mattered. The slide says it in six words: too much input data, hard to fit to an LLM.

The device shows the fit. Drag the size of the chart and choose a window. Both numbers are illustrative; real chart sizes and real windows vary.

Will the chart fit?

The blue bar is the chart in tokens. The outlined bar is the window. Any part of the chart past the window edge is red: it never reaches the model.

150,000

Illustrative: the chart sizes and the three window sizes are made up for the picture. The lecture says only that there is too much input to fit an LLM. The window sizes are small steps of a common pattern, not the specs of any one model.

A short chart fits. A long ICU stay does not. When it does not fit, the builder must choose what to drop, and nothing in the recipe tells her how to choose well. Chapter 4 gives the fix: pick the relevant parts first.

Complaint two: unsupervised, and poorly calibrated

The model never saw a labelled patient from this hospital. No one trained it to be right about pleural effusion. The slide calls this unsupervised: the predictions are not tuned for accuracy. Its probabilities are also “poorly calibrated”.

Calibration asks whether a stated probability means what it says. Take every case where the model says 90%. A calibrated model is right in about 90 of 100 of them. An overconfident model says 90% and is right in 70. In medicine, a probability is a promise, so an uncalibrated one misleads. Try the dial.

Trust the number?

The dashed diagonal is a calibrated model: stated and actual agree. The curve is a model that is too sure of itself. Drag the dial to make it more overconfident.

0.60

Toy curve, not a measurement: actual = 0.5 + (stated − 0.5) × (1 − 0.6 × overconfidence). The lecture says only that the zero-shot predictions are poorly calibrated.

Complaint three: not trained on our data

The last complaint is about training. The model was never finetuned, meaning trained further, on this hospital’s patients. The slide adds that finetuning a proprietary LLM on sensitive patient data is not trivial. Patient files are private. Sending them to another company to train a model is hard to allow, and for some models it is not offered at all.

What the numbers say

The lecture’s results (slide 16, Chapter 8) show a mixed picture, and we should be fair to the zero-shot model. On the three pathology tasks it beats HAIM: 89.9 against 76.3 on pneumonia. Reading text helps when the answer is written in the text. On outcomes it is weaker. On mortality it scores 78.5 against HAIM’s 82.0. On length of stay it scores 44.7, below the 50 of a coin flip.

That last number is the failure in three steps. Symptom: the model sounds confident about how long a patient will stay. Measurement: 44.7 on the lecture’s test, worse than guessing. Fix: use the language model to prepare the data, then let a classifier trained on real outcomes make the prediction. That is xHAIM’s split of the work.

A zero-shot model answers “90%” for many patients, and is right for 70 of every 100 of them. Which complaint from slide 6 does that show?

Chapter 3

The xHAIM Plan: Read First, Then Predict, Then Explain

Walk the five steps of xHAIM and learn how a table row, a lab series and an X-ray all become sentences

Picture a good medical student on a night shift. She does not read the whole file from page one. She asks what the doctor needs to know, finds the pages that speak to it, writes a short note, and only then makes a call. Later she can point at the pages she used.

xHAIM works the same way. Slide 7 lists five steps, numbered 0 to 4, in three groups. Each group answers one of the weak spots from Chapters 1 and 2.

The five steps

  1. Step 0, define the task and its keywords. Write what you want to predict, with words that point at it, such as “hypertension”.
  2. Step 1, find the most relevant patient data. Pick the parts of the file that speak to the task.
  3. Step 2, produce a single summary. Write one short text that covers all the patient information for that modality.
  4. Step 3, feed the summaries into HAIM. Use them in place of raw data, for better predictions.
  5. Step 4, combine three things for generative AI explanations. The three are the machine-learning prediction, the summaries together with the raw patient data, and medical knowledge.

The slide groups them. Steps 0 to 2 improve the input, and the slide says they solve “too much data”. Step 3 improves the predictions. Step 4 gives explainability and solves the “transparency” problem. Press the numbers below to light up each step.

Walk the plan

Five steps in order. The left bracket names what a group improves. The right tag names the weak spot it answers. Press a step.

The step names, the three groups and the two “solves” tags are from slide 7. The one-line effect of each step is our wording of the slide.

Notice what xHAIM keeps. Step 3 still uses HAIM and its classifier. The change is in what flows into it and in the extra step that explains. Chapters 4 to 7 build steps 1 to 4 in order.

Converting every modality to text

Before steps 1 and 2 can work, every modality must be text. Why text? Text is the one form that a language model, a retrieval tool and a human reader all understand. Slide 8 gives the rule for each modality.

  1. Tabular and time series: convert to natural language with a fixed template. The slide shows two: “Patient is a 80 year old male. Patient is prescribed 100 mg of Insulin.” and “Patient’s average blood pressure is 60/120 mmHg, with its last measurement being 75/130 mmHg.”
  2. Images: pass the image and its report together, as a prompt, to a multimodal LLM, a language model that can also look at pictures. The slide names Qwen as an example. The output is a text description.
  3. Notes: use as they are. They are text already.

A footnote on the slide adds a caution. Tabular and time-series data can also just go through the original HAIM path, because the gain from xHAIM is smaller for them than for images and notes. The reason is easy to see: a row of numbers has little to summarise.

Images, step by step

The image path is the one with a model inside, so follow it slowly. The input is a chest X-ray, a grid of pixel values, together with the radiologist’s report, a string. The multimodal model reads both. The output is a paragraph that says what the picture shows.

Why pass the report as well? The report tells the model what the human expert already saw, so the model can focus on describing and does not have to diagnose from scratch. The slide shows both going into the prompt. There is a cost: a description can state a finding that is not in the picture. That risk is one more reason Chapter 7 requires citations that point back to raw text.

A template, in code

A template is a fill-in-the-blanks sentence. It is plain code, with no model inside, so it is fast and cannot invent facts.

def row_to_text(r):                                  # r: one patient's table row (a dict)
    return (f"Patient is a {r['age']} year old {r['sex']}. "
            f"Patient is prescribed {r['dose_mg']} mg of {r['drug']}.")   # str

def series_to_text(sys, dia):                          # two lists of hourly numbers
    return (f"Patient's average blood pressure is {mean(sys):.0f}/{mean(dia):.0f} mmHg, "
            f"with its last measurement being {sys[-1]}/{dia[-1]} mmHg.")

text_img = vlm(image=xray, report=report_text,             # (H, W) pixels + str in, str out
               prompt="Describe the findings.")

The time-series function throws away most of the series. A day of hourly readings becomes a mean and a last value. That loss is on purpose: the summary keeps what a doctor would say aloud. The device lets you feel it. Move the sliders and read the sentences they produce.

From numbers to a sentence

The sliders are the table row and the blood-pressure series. The two boxes show the sentences a template writes. Change a number and watch the words change.

80
100
120
130

The two templates follow slide 8. We write blood pressure as systolic over diastolic, and the diastolic values (60 average, 75 last) stay fixed, so you move only the first number. The slide’s own example writes the pair the other way round. The sex is fixed at male as on the slide.

The read-out counts words. At the starting numbers the table row became 14 words, and a whole day of readings became 14 more. That is the scale xHAIM works at: short, readable pieces that a search tool and a language model can both use.

Which group of xHAIM steps does the slide say solves “too much data”?

Chapter 4

Part 1: Find the Relevant Data

Cut a long record into chunks, score each chunk against a task sentence, and keep only the best

A librarian gets a request: “Anything about this patient’s blood pressure.” She does not read every shelf. She has a way to score each page against the request, and she pulls the top few. xHAIM’s first part does exactly this for a patient file.

Slide 9 shows the idea as a four-box strip. Patient notes go in. They are split into smaller chunks. Each chunk is scored against the task. The most relevant notes come out. The strip is drawn for notes, the modality with the most text, but the same step applies to any modality once it is text (Chapter 3).

The task sentence

First, say what you are looking for. The lecture defines a task sentence: a short run of words that all point at the target. Its example for hypertension is: “essential hypertension, hypertensive, high blood pressure, HTN, systolic, diastolic”. See what it holds: the formal name, the adjective, the plain-words name, a common abbreviation, and two measurements. A note might use any of them, so the sentence lists them all.

Chunks

A note can run to many pages, and a single page can hold a hundred facts. Scoring a whole note against the task would blur everything together. So the notes are cut into chunks, small pieces of text, about a few sentences each. Each chunk then gets its own score. Our text chunking lesson shows how to choose chunk sizes.

Two ways to score a chunk

The lecture scores each chunk with a combination of two measures, listed in the slide’s footnote. They catch different kinds of match.

Embedding similarity. Turn the task sentence into an embedding St (Chapter 1). Turn each of the N chunks into embeddings S1 to SN. A chunk whose embedding sits close to St means about the same thing. Take the top k chunks, for example the top 10. The strength: a chunk that says “elevated arterial tension” scores well even though it shares no word with the task sentence. The weakness: a bare abbreviation like “HTN” carries little meaning on its own. (How to measure closeness, how embeddings are made.)

BM25. This is the classic keyword score, from search engines. It counts how often the task words appear in a chunk. Two ideas make it smarter than a plain count. A word that is rare across all chunks counts for more (“hypertension” says more than “pressure”). And repeating a word helps less each time, with a small bonus for short chunks. The strength: it finds the exact string “HTN”. The weakness: it misses a paraphrase.

A worked BM25 score

Take the ten toy chunks in the device below. The average chunk holds 9.3 words. The chunk “HTN, DM2, CKD stage 3.” holds 5 words and matches one task word, “htn”. That word appears in 1 of 10 chunks, so its rarity weight is ln(1 + (10 − 1 + 0.5)/(1 + 0.5)) = 1.99. We use the usual constants, k = 1.2 and b = 0.75, so:

1.99 × (1 × 2.2) / (1 + 1.2 × (0.25 + 0.75 × 5/9.3)) ≈ 2.46

The best chunk, “high blood pressure for ten years”, matches three task words and scores 5.30. Divide each score by the best one and the short chunk gets 0.46. That is the “words” number the device shows. The “meaning” numbers are hand-set for the toy, in the style of the slide’s 0.95, 0.87, 0.81 and 0.67.

Rank the chunks

Ten chunks from a toy chart, scored against the hypertension task sentence. Slide the mix between meaning and words, and the number of chunks to keep. Highlighted words are keyword matches.

50%
4

    The word scores are real BM25 (k = 1.2, b = 0.75) over these ten chunks, computed live in your browser and divided by the best chunk. The meaning scores are hand-set for the picture, because the page does not run an embedding model. The slide says “a combination” of the two scores and gives no weights; the weighted sum is our simple choice.

    At 100% meaning, the abbreviation chunk drops to sixth place, behind two chunks that only hint at pressure. At 0% meaning, the paraphrase “elevated arterial tension” scores zero and never gets in. A mix keeps both. That is why the lecture combines them.

    The failure and the fix

    Symptom: the final summary leaves out the one note that mentioned a blood-pressure drug. Measurement: list the rank of that note under each score. If it is rank 9 under meaning and rank 2 under words, one score alone would have dropped it. Fix: blend the scores, and raise k a little for tasks whose evidence hides in short or oddly worded notes.

    Here is the step as code. It takes a list of chunk strings and returns the top few, with shapes.

    chunks = split(note, size=300)                   # N strings
    s_t = embed(task_sentence)                          # (d,)
    S   = embed(chunks)                                 # (N, d)
    emb = (S @ s_t) / (norm(S, axis=1) * norm(s_t))     # cosine, (N,)
    kw  = bm25(chunks, query=task_sentence)             # (N,)
    score = a * rescale(emb) + (1 - a) * rescale(kw)       # one number per chunk
    keep  = [chunks[i] for i in np.argsort(-score)[:k]]   # top-k chunks
    A chunk reads “Elevated arterial tension noted by the night nurse.” Which score is most likely to find it, and why?

    Chapter 5

    Part 2: Write One Summary for Each Modality

    Turn the best chunks into one short, uniform paragraph, and see how much shorter it is than what it replaces

    At the end of a shift, a nurse hands over her patients. She does not read out the chart. She says: “Eighty-four, bypass surgery in 2017, high blood pressure, diabetes with kidney disease.” It takes ten seconds. The next nurse knows what matters.

    Part 2 of xHAIM does the same job with a language model. The input is the most relevant patient data from Part 1: the three chunks on the slide, numbered 1, 2 and 3. The output is a summary, one paragraph that holds the important facts and leaves out the rest.

    What the lecture asks for

    The slide states the goal in one sentence: create a uniform, comprehensive paragraph that summarises the information from the patient’s most relevant chunks for the specific modality. Look at each word.

    The slide shows an example summary for the notes: “The patient is a 84-year-old male who underwent coronary artery bypass grafting on October 31, 2017, for three-vessel coronary artery disease. His medical history includes essential hypertension, type 2 diabetes mellitus with stage 3 chronic kidney disease, and a history of abdominal aortic aneurysm repair.” Two sentences carry five facts.

    The data flow

    The input is a list of text chunks. The output is one string. A summariser is one call to a language model. Here is the call, with our own prompt wording, since the lecture does not print one.

    chunks = top_k_chunks(notes, task_sentence)          # list of k strings, ~300 words each (illustrative)
    prompt = ("Write one paragraph about this patient's "
              "history using ONLY the text below. Keep facts "
              "about: " + task_sentence + "\n\n" + "\n---\n".join(chunks))
    summary = llm(prompt)                                # one string, ~60 words

    Note the phrase “using ONLY the text below”. A language model can invent plausible facts. The instruction asks it not to, and Chapter 7 adds a stronger check: citations that point back to the raw text.

    Compression you can measure

    The slide says the summary is much more compact than the previous input, which can be thousands of words. Measure the gap with the device. It builds the slide’s own summary one fact at a time as you keep more chunks. We assume each chunk holds 300 words and that the first four chunks each add one new fact. The later chunks add nothing new.

    Build the summary

    Drag the number of chunks the summariser reads. The bars compare words in with words out. The paragraph below shows the summary the slide gives, with missing facts still blank.

    3

    The summary text is the slide’s example for the notes. The chunk length (300 words) and the rule that the first four chunks each add one new fact are illustrative, not from the lecture; the word counts are measured live from the text on this page.

    Three chunks are 900 words. The summary is 38 words, about four percent of the input. Keep all ten chunks and the input is 3,000 words, while the summary stays at 45 words: it only grows when a chunk brings a new fact. This is the point of a uniform, compact paragraph. The cost of the later parts depends on the summary length, not on how long the stay was.

    What it costs to run

    A summary is one language-model call for each patient, modality and task. Take a hospital with 1,000 patients and four modalities. One task needs 4,000 calls. A second task needs 4,000 more, because each task has its own task sentence and so its own summaries. That arithmetic is ours and illustrative; the lecture does not give a cost. It shows why the chunks must be few and short. Fewer words in means a cheaper and faster call.

    Uniform text also pays off later. In Chapter 6 an encoder is finetuned on these summaries. If every summary has the same layout (who, what happened, history), the encoder sees one familiar shape again and again, and it learns the task faster than it would from notes that each look different.

    A failure to watch for

    Symptom: the summary says “history of stroke” and no chunk mentions a stroke. Measurement: check every claim in the summary against the chunks; one claim has no source. Fix: tell the model to use only the given text, keep the chunks short enough to check, and cite sources in the explanation step. A summary is a lossy copy, so we must check it and not simply trust it.

    There is also a quieter loss. A summary written for a hypertension task may drop a fact a different task needs. That is why the lecture starts from a task sentence: each task gets its own summary. The cost is one extra run for each new task. The gain is that each summary is tuned to its question.

    As the summariser reads more and more chunks, what happens to the words in and the words out?

    Chapter 6

    Parts 3 and 4: Tune the Encoder, Then Classify

    Finetune a pretrained text model on this hospital’s summaries, glue the four embeddings together and train the final classifier

    A new nurse arrives from another hospital. She is well trained, but her old ward used different shorthand and saw different patients. After a few weeks on your ward she reads your charts faster. She did not forget her training. She tuned it to your data.

    That is Part 3. In the original HAIM pipeline, every modality went through an encoder that had been pretrained: trained earlier, on a very large body of data that is not yours. The slide gives two examples, DenseNet for images and ClinicalBERT for notes. These encoders are good in general. They were never tuned to your hospital.

    Why xHAIM can finetune

    The lecture makes a pointed argument. Because the summaries are short, and because every modality is now plain text, a pretrained text model can be finetuned on them. Finetuning means continuing to train a pretrained model on your own labelled examples, so its internal numbers shift toward your data. The result is a representation “more tailored to our specific dataset”.

    Two facts make this possible. Short input: a standard BERT model reads at most 512 tokens, so a 45-word summary fits easily while a pile of raw notes would not. One kind of input: when every modality is text, one recipe covers all of them. The slide draws the result as a box for each modality: the generated summary goes into ClinicalBERT, a BERT model pretrained on clinical notes, and it comes out as the embedding Enotes.

    How finetuning works, in plain steps

    The lecture does not spell out the training loop. This is the usual way, and the lesson’s own wording.

    1. Take the pretrained encoder. It maps a summary to one embedding.
    2. Add a small head. A head is a tiny layer on top that turns the embedding into a score for the task, such as hypertension.
    3. Train on labelled summaries. For each patient, compare the head’s score with the true label, and nudge all the weights to shrink the gap.
    4. Throw the head away, keep the encoder. The tuned encoder now maps a summary to an embedding that already separates patients by the task.
    tok = tokenizer(summary, truncation=True, max_length=512)   # ids, shape (L,) with L <= 512
    h   = clinicalbert(tok)                                       # (L, 768) one vector per token
    e   = h[0]                                                    # (768,) the [CLS] vector = E_notes
    logit = head(e)                                               # one number, trained against the label
    loss = bce(logit, label)                                      # shrink the gap, update all weights

    The sizes in the code are those of the standard BERT base model; the slides give no sizes. Do this for each modality’s summary and you have one tuned embedding per modality.

    See what tuning does

    The device is a toy of one idea: finetuning moves patients with the label to one side and patients without it to the other. The dots are 80 patients in a made-up two-number embedding. Blue dots are patients with hypertension, pink dots are patients without. To check whether the picture is useful, we ask a simple question of each held-out patient: do the three nearest labelled patients share its label?

    Finetune the encoder

    Each dot is one patient. Drag the slider from the generic pretrained encoder (step 0) to the finetuned one (step 100). Open dots are held out: the check uses only the filled dots to label them.

    0

    Toy data, made by a fixed seed: 80 points in two dimensions (real embeddings have hundreds), the two groups overlapping at step 0 and about three spreads apart at step 100. The accuracy is a real three-nearest-neighbour check on the 40 held-out points. The lecture reports no such numbers; it claims only that finetuning gives representations tailored to the dataset.

    At step 0 the check is only a little better than a coin flip: 23 of 40. At step 100 it labels 37 of 40 held-out patients correctly. The data did not change. Only the map from text to numbers changed. A classifier reading the tuned embeddings has an easier job.

    Part 4: the final classifier

    Now put the pieces together, as slide 13 draws them. The four embeddings are concatenated, exactly as in HAIM, and fed to the final classification model. Look at which paths are new. The tabular and time-series paths can stay as they were in HAIM (the footnote on slide 8 explains why). The image and notes paths now pass through the xHAIM pipeline: find the relevant data, summarise, finetune the encoder. The classifier is then trained for the task, to say yes or no.

    e_tab = haim_encoder_tab(row)          # (d1,)  as in HAIM
    e_ts  = haim_encoder_ts(series)        # (d2,)  as in HAIM
    e_img = tuned_bert(summ_images)        # (768,) from the xHAIM image summary
    e_txt = tuned_bert(summ_notes)         # (768,) from the xHAIM notes summary
    x = np.concatenate([e_tab, e_ts, e_img, e_txt])   # one vector per patient
    p = final_classifier.predict_proba(x[None])[0, 1]   # the task probability

    The slide gives the reason it works: the data quality used to train the model is “significantly increased” compared with the baseline. Cleaner, task-focused inputs and tuned embeddings give the classifier less noise to fight. Chapter 8 shows the size of the gain.

    One failure to guard against. Symptom: the tuned model scores very high on the patients it trained on and poorly on new ones. Measurement: the gap between training score and held-out score, as the device’s open dots show. Fix: always keep patients out of training and score on them, and stop tuning when the held-out score stops rising. That caution is ours; the lecture does not discuss it.

    According to the lecture, why can xHAIM finetune an encoder when the original HAIM could not do it as usefully?

    Chapter 7

    Part 5: An Explanation You Can Check

    Hand a generative model the prediction, the summary, the raw chunks and medical knowledge, and require a citation for every claim

    The classifier says 1.00: pleural effusion, a build-up of fluid around the lung. The doctor asks the obvious question. “Why?” An answer like “because the numbers said so” is useless. An answer like “because the report from May 25 says so, and here is the sentence” is something she can check in seconds.

    Part 5 builds that second kind of answer. The lecture calls the result a grounded and factual explanation. Grounded means each claim points to a specific piece of the patient’s own record. A reader can follow the pointer and see for herself.

    What goes in

    Slide 14 draws four inputs flowing into a generative AI model. The lecture lists them in text as well.

    1. The relevant chunks from Part 1, numbered 1, 2, 3 and so on. These are the raw words from the chart, and they are the evidence a claim can point to.
    2. The generated summary from Part 2, which gives the model the overall picture.
    3. The machine-learning prediction: the label and the probability from the classifier of Chapter 6.
    4. Medical knowledge. The slide shows the logos of Mayo Clinic, MedlinePlus and PubMed. Knowledge lets the model say what a finding means, not just that it appears.

    The output is a short explanation with citations in square brackets that refer to the numbered chunks. The prediction comes from the classifier and the words come from the generative model. The two jobs stay apart. The classifier is trained on outcomes, so its probability is meaningful. The generative model is good at writing and at reading medical text, so it explains.

    The request and the reply

    Here is the call in shape. The wording is ours; the lecture shows the four inputs and an example answer, not the prompt.

    chunks = ["[1] ap chest, man with a right apical pneumothorax. impression. small left pleural effusion is likely.",
              "[2] single frontal view of the chest. ... small bilateral pleural effusions. ..."]
    prompt = f"""Prediction: pleural effusion = 1 (probability 1.00)
    Summary: {summary}
    Knowledge: {knowledge_snippets}
    Evidence chunks:
    {chr(10).join(chunks)}
    
    Explain the prediction. Cite chunks as [n]. Quote the words you rely on.
    Say if any chunk contradicts the prediction. Use only the evidence above."""
    explanation = llm(prompt)            # one string with [1], [2] markers

    The lecture’s example reply (slide 19) opens: “The patient has been predicted to have pleural effusion (prediction 1) with a model output probability of 1.00, based on consistent documentation of pleural effusion across multiple radiology reports.” It then names the strongest evidence: the most recent chest note [1], which describes “small left pleural effusion is likely”, and the second most recent report [2], which mentions “small bilateral pleural effusions”. It adds that no document contradicts the prediction. Four parts: the prediction, the evidence with citations, a contradiction check, and a reading of the confidence.

    Check the claims yourself

    The device holds that explanation, cut into four claims. Press a claim to see its evidence light up in the raw notes. Then change which notes the model was given. The device checks each quote against the notes, with real string matching. Claim four is one we invented, to show what an unsupported claim looks like.

    Follow a claim to its evidence

    Press a claim. The words it relies on light up in the note it cites. Use the choices to change which notes the model was given, and watch claims lose their support.

    Claims one to three and both notes are slide 19’s example (notes quoted from the slide, abbreviated). Claim four, about a pleural tap, is our invention to show a claim with no source. The check is real: a claim counts as supported only if the model was given the note it cites and the quoted words appear in that note.

    Press claim two and the words “small left pleural effusion is likely” light up in note [1]. Leave note [2] out and claim three turns red: it cites evidence the model never saw. Claim four is unsupported even with both notes, because “pleural tap” appears nowhere in them. A reader who follows the pointers would catch that in seconds. A reader of a bare probability could not.

    The failure and the fix

    Symptom: the explanation sounds right, but one citation points at the wrong note, or at a note number that does not exist. Measurement: for each claim, look up the quote in the chunk it cites. If it is missing, the claim is ungrounded. You can run this check by program. Fix: reject or regenerate any explanation whose quotes fail, and tell the reader which claims passed. Chapter 9 shows how the lecture scores explanations at scale.

    One more point on honesty. The prediction and the explanation come from different parts of the system. The explanation says why the evidence supports the label. It does not show how the classifier’s internal numbers produced it. The lecture’s own words are careful: the explanation is grounded in the raw patient data. That is a claim about evidence, and a useful one, but it is not a view inside the classifier.

    An explanation says “the strongest evidence is note [3], which reports a pleural tap.” Only notes [1] and [2] were given. What is the right verdict?

    Chapter 8

    Did the Predictions Get Better?

    Learn what ROC AUC measures by playing with it, then read the lecture’s five results with the right question in mind

    A hospital runs two models on the same 1,000 patients. Model A is right on 840. Model B is right on 830. Is A better? Maybe. If only 50 of the patients are sick, a model that says “healthy” to everyone is right 950 times and helps no one. We need a score that rewards ranking the sick above the healthy.

    The experiment

    Slide 15 sets the stage. The authors used MIMIC-IV, a collection of records from intensive-care patients. They took demographics, lab values, chest X-rays, and the radiology and process reports. Then they chose two kinds of task.

    1. Information-extraction-like tasks. The answer can be read from the input: pneumonia, pleural effusion and cardiomegaly (an enlarged heart). The record states or implies the answer.
    2. Prospective outcomes. The answer lies in the future: death within 48 hours, and a stay in the ICU longer than 7 days. The record does not state these.

    Keep this split in mind. It explains the shape of the results.

    ROC AUC from zero

    The slide scores every method with ROC AUC. The name stands for the area under the ROC curve, but a simpler meaning is easier to hold. Pick one patient who really has the condition and one who does not, both at random. Look at the scores the model gave them. AUC is the chance that the sick patient got the higher score.

    That gives the whole scale. A model that guesses scores 0.5, or 50 in the slide’s percent form: the sick patient wins half the time. A perfect model scores 100: the sick patient always wins. A model below 50 ranks worse than chance. AUC cares only about the order of scores, not their size, so it ignores calibration (Chapter 2). It also ignores the base rate: a rare disease and a common one are scored alike.

    Try it. The two clouds are the scores of 100 sick and 100 healthy patients. Slide the separation, then draw random pairs and tally who wins.

    Play with AUC

    Pink dots are the scores of healthy patients, blue dots of sick patients. Slide the separation, then press Draw a pair several times. Each draw picks one of each and checks who scored higher.

    1.2

    Toy scores from a fixed seed: 100 healthy patients from a bell curve at 0 and 100 sick patients from the same bell curve shifted by the separation. The AUC shown is exact over all 10,000 pairs. The draws are real random draws. None of this is the lecture’s data.

    At separation 0 the two clouds sit on top of each other and AUC is near 50. At 3.5 the clouds barely touch and AUC is near 99. Your tally of drawn pairs wobbles around the exact number and settles as you draw more. That is all AUC is: a count over pairs.

    The lecture’s results

    Slide 16 plots the five results. Here they are, in the lecture’s percent form, with our column for the gain.

    TaskKindHAIMZero-shot LLMxHAIMxHAIM minus HAIM
    Pneumoniaextraction-like76.389.996.7+20.4
    Pleural effusionextraction-like84.893.798.6+13.8
    Cardiomegalyextraction-like81.191.198.2+17.1
    Length of stay over 7 daysoutcome75.544.777.7+2.2
    Mortality within 48 hoursoutcome82.078.585.1+3.1

    Three readings stand out. First, xHAIM wins every row. Second, the gains split in two groups. On the extraction-like tasks they are 13.8 to 20.4 points. On the outcomes they are 2.2 and 3.1 points. The lecture’s conclusion slide says “up to 2 to 20%”, which is this range. Third, the zero-shot model is strong on the first group (beating HAIM by 9 to 14 points) and weak on the second, where it falls to 44.7, under a coin flip, on length of stay.

    Why the split? It is our reading, not a claim from the slide. When the answer is written in the notes, a pipeline that finds and condenses the right sentences gives the classifier a clear signal. When the answer is a forecast, the notes hold only hints, and no amount of tidying creates facts that are not there. xHAIM still helps, but modestly.

    Go back to the hero at the top of the page and press through the five tasks. You can now read each bar as a chance that a sick patient outranks a healthy one.

    A failure to guard against

    Symptom: two models have the same AUC but one makes a doctor’s alerts far noisier. Measurement: AUC ignores the size of the scores and the base rate, so compare calibration (Chapter 2) and the number of false alarms at the threshold you will use. Fix: report AUC together with a calibration check and the alert rate. The lecture reports AUC alone for these five results.

    A model has a ROC AUC of 44.7. What does that mean?

    Chapter 9

    Grading Explanations at Scale

    Score explanations with a rubric, check a language-model judge against human graders, then let it grade a thousand

    The team now has a thousand explanations. Which are good? A prediction has an answer key: the patient lived or died. An explanation has none. Someone must read it, open the patient’s notes, check each claim and give a grade. A clinician takes minutes per case. A thousand cases take weeks.

    Slide 17 shows the team’s way out. It has three steps: write a clear rubric, have humans grade a small sample, and then replace the humans by a language model whose grades match theirs.

    Step 1: the rubric

    A rubric is a written scoring guide. The slide describes a system with three main categories, and a “thorough” rubric under them. Each category answers one question.

    1. Citation quality. Are the citations accurate? Does each [n] point to a chunk that really says what the claim says?
    2. Factual correctness. Are the claims based on actual evidence in the patient’s documents?
    3. Overall quality. Is the explanation clear, concise and logically sound? The slide names verbosity here.

    The three are separate on purpose. An explanation can cite correctly and still be rambling. It can be fluent and cite nothing. One grade would hide which failure happened.

    Step 2: human graders

    Human annotators used the rubric on 50 outputs for pleural effusion and 50 for mortality. The slide calls them “summaries”; they are the generated explanations. A hundred cases is a small job for people.

    Step 3: the language-model judge

    The LLM-as-a-judge idea is to ask a second language model to grade the first one’s work. The slide’s figure shows three inputs going into an evaluator: the AI explanation, the patient documents, and the evaluation criteria. It outputs scores for three questions: factuality (are claims based on actual evidence?), citation (are citations accurate?) and quality (is the explanation clear, concise and logically sound?).

    The slide describes a two-pass setup. One model generates critiques. The other reads the explanation and the critique and assigns the final scores to the same cases. Writing a critique first forces the judge to look for specific faults before it scores. In code the shape is:

    critique = llm_a(explanation, documents, rubric)            # str: a list of faults found
    scores   = llm_b(explanation, documents, rubric, critique)  # dict: {"citation": 4, "factuality": 4, "quality": 3}

    The trust check

    Why believe the judge? The lecture’s answer: first show that its scores match the human scores. After establishing “adequate overlap between the score distributions” of the human annotators and the judge, the team trusted the judge and used it to evaluate 1,000 explanations.

    The device tests this idea. It holds 50 toy cases. Humans gave each a score. The judge gives a score that is the human score plus some noise. Slide the noise, then switch to a judge whose scores have the same overall spread but are shuffled between cases.

    Can the judge be trusted?

    Each dot is one explanation: human score across, judge score up. Dots on the diagonal are cases where the two agree. The three numbers below measure how well the judge tracks the humans.

    0.40

    Toy data from a fixed seed: 50 human scores centred near 3.8 (clamped to 1 to 5) and judge scores made from them. The overlap is the shared area of two histograms with bins half a point wide. The lecture reports that overlap between the human and judge score distributions was adequate; it gives no figures, and the per-case agreement and correlation are our added check.

    Switch to the shuffled judge. The two histograms overlap just as much as before, because the shuffle keeps every score and only moves them between cases. Yet the dots scatter into a cloud and the correlation drops to near zero. This shows what overlap can and cannot tell you. Matching score distributions are necessary: a judge that gives everything 5 fails at once. They are not sufficient. The case-by-case check is the stronger test, and a careful team would add it.

    The lecture’s verdict on 1,000 cases

    Slide 18 shows the judge’s average scores for the two tasks. Reading the bars of the chart (the values are approximate, read off the slide), pleural effusion scores about 4.1 on citation and about 4.1 on factuality, and about 3.9 on quality. Mortality scores about 3.5 on citation, about 3.5 on factuality, and about 3.9 on quality.

    The lecture explains the gap. “Mortality within 48 hours” is harder to explain because it is difficult even for humans to find evidence for such an outcome in the relevant documents. This fits Chapter 8. Pleural effusion is written in the radiology notes, so a citation exists. Whether a patient dies in two days is a forecast, so the best citation is only a hint. Quality, which asks about clarity, stays about the same, because writing clearly does not depend on finding a perfect quote.

    The failure and the fix

    Symptom: the judge gives a fluent explanation a 5 even though its quote is invented. Measurement: compare judge and human scores on cases a human checked against the documents; the disagreement clusters on fluent but ungrounded text. Fix: give the judge the patient documents (the slide’s figure does), make it critique first, and re-run the human check whenever you change the judge model or the rubric.

    Why is it not enough to show that a judge’s overall score distribution matches the humans’?

    Chapter 10

    The Field Guide

    Keep the numbers, the terms, the checklist and the core code from the whole lecture on one page

    The lecture ends with two claims on slide 20. Improved performance: find the data that matters for the task, let downstream models read dense summaries instead of raw data, and gain 2 to 20 points of AUC. Improved explainability: ground each explanation in the actual raw patient data. Everything in the lecture serves one of those two lines.

    The story in one paragraph. Patients come with four modalities. HAIM embeds them all and glues them, which is noisy and opaque. A zero-shot language model reads everything as text, which overflows, miscalibrates and cannot be tuned. xHAIM turns everything into text, finds the relevant chunks with a task sentence, writes one summary per modality, finetunes an encoder on those summaries, trains a classifier, and asks a generative model for an explanation that cites the raw notes. A rubric and a checked language-model judge then grade the explanations.

    Try the pipeline without a part

    Each part exists because of a weak spot. Switch parts off and see which weak spot returns.

    Remove a part

    All five parts start on. Switch one off and read which problem from the lecture returns.

      The pairing of each part with its weak spot comes from slides 4, 6, 7, 11 and 13. The lecture ran its experiments with the full pipeline, so this device shows the logic of the design, not measured ablations.

      The numbers

      ItemValueSlide
      xHAIM steps0 to 4: task and keywords, relevant data, one summary, HAIM prediction, GenAI explanation7
      Chunks kept (example)top-k, for example k = 10, by embedding similarity combined with BM259
      Pneumonia ROC AUCHAIM 76.3, zero-shot 89.9, xHAIM 96.716
      Pleural effusion ROC AUC84.8, 93.7, 98.616
      Cardiomegaly ROC AUC81.1, 91.1, 98.216
      Length of stay (over 7 days) ROC AUC75.5, 44.7, 77.716
      Mortality (48 hours) ROC AUC82.0, 78.5, 85.116
      Human-graded explanations50 for pleural effusion, 50 for mortality17
      Judge-graded explanations1,000, after human and judge scores overlapped17, 18
      Reported gainup to 2 to 20 points of AUC, additive20

      The terms

      TermPlain meaning
      ModalityOne form of data: table, time series, image, text.
      EmbeddingA fixed-length list of numbers that stands for a record.
      FusionJoining the modalities, here by placing the embeddings end to end.
      Zero-shotUsing a model with no examples and no training on your data.
      CalibrationWhether “90%” is right about 90% of the time.
      Task sentenceWords that point at the target, used to find relevant chunks.
      BM25A keyword score that weights rare words and saturates repeats.
      FinetuningFurther training of a pretrained model on your labelled data.
      ROC AUCThe chance that a random sick patient outscores a random healthy one.
      GroundedEach claim points to a place in the raw record.
      LLM-as-a-judgeA language model that grades another model’s output against a rubric.

      The checklist

      1. Write a task sentence with the formal name, the plain name, abbreviations and the measurements.
      2. Convert every modality to text. Keep tables and series on the HAIM path if text adds little.
      3. Rank chunks by meaning and by keywords together. Check that abbreviations and paraphrases both survive.
      4. Summarise from the chunks only. Compare the summary with its chunks.
      5. Finetune on training patients, and score on held-out patients.
      6. Report AUC with a calibration check and the alert rate.
      7. Make the explanation cite chunk numbers, and check every quote by program.
      8. Trust a judge only after it matches human grades case by case.

      The core as code

      def xhaim_predict_and_explain(patient, task):
          kw    = task.sentence                                       # step 0: task sentence (str)
          texts = {m: to_text(patient[m]) for m in MODS}                # tabular, series, image, notes -> str
          best  = {m: top_k(chunk(texts[m]), kw, a=0.5, k=10) for m in MODS}   # step 1: list of chunks
          summ  = {m: llm_summarise(best[m], kw) for m in MODS}          # step 2: one paragraph each
          emb   = {m: tuned_encoder[m](summ[m]) for m in MODS}         # step 3: (768,) each
          x     = np.concatenate([emb[m] for m in MODS])              # fusion: one vector
          p     = classifier[task.name].predict_proba(x[None])[0, 1]
          expl  = llm_explain(p, summ, best, knowledge(task))         # step 4: text with [n] citations
          assert all_quotes_found(expl, best)                        # reject ungrounded output
          return p, expl

      Where it sits, and where to go next

      xHAIM is retrieval, summarisation, finetuning and generation chained around a classifier. If you know those four, you know its parts. Our lessons cover them: chunking, embeddings, similarity, retrieval-augmented generation (the same “find, then write with citations” pattern), finetuning in practice, evaluation, and calibration.

      For the sources, start with the xHAIM paper, then the baseline it extends: Soenksen et al., Integrated multimodal artificial intelligence framework for healthcare applications, npj Digital Medicine 5, 149 (2022), doi 10.1038/s41746-022-00689-4. The lecture’s opening slide also points to The Gradient’s article on human-centered explainable AI.

      The takeaway. Do not ask one model to read everything and decide. Find what matters, write it down short, predict with a model trained on real outcomes, and explain with sentences that point back to the record.

      Now go back to the score bars at the top and press through the five tasks again. Then open Teach and explain the five parts of xHAIM on a whiteboard, or use Present to say them aloud. Credit: this lesson re-teaches Lecture 9.2 of MIT MMAI, Multimodal AI (Spring 2026), from the MIT Multisensory Intelligence group led by Paul Liang. The slides are here, and the method is from the paper by Periklis Petridis, Georgios Margaritis, Vasiliki Stoumpou and Dimitris Bertsimas.

      MMAI L9.2: Explainable Reasoning
      The course site · Read the paper · Back to Gleams