Skip to content
BIASED
Back to topic

Optional

Hazards: forwarding vs stall

On a 5-stage pipeline for 3 instruction pairs choose forward, stall, or none; count bubbles.

Version
v2
Minutes
~20
Evidence
Self-check in the notebook

Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.

Download .ipynb

Download the notebook and run it locally. Its environment requirements are listed inside.

Notebook contents

Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.

CA · Хазарды: forwarding vs stall / Hazards: forwarding vs stall

Activity version: 2 · Seed: n/a · Данные: three instruction pairs on a classic 5-stage IF–ID–EX–MEM–WB pipeline.

For each pair choose forward, stall, or none; count bubbles with and without forwarding.

Ожидаемые числа
Pair Dependence with forwarding without forwarding
add→sub (ALU→ALU) yes forward, 00 bubbles 22 bubbles
lw→add (load-use) yes stall, 11 bubble 22 bubbles
independent add/xor no none, 00 00
total bubbles 11 44
Самопроверка в ноутбуке

Активность не входит в процент освоения.

import numpy as np
 
# Each insn: (op, rd, rs1, rs2) — rs2=None for lw-style
pairs = [
    (("add", 1, 2, 3), ("sub", 4, 1, 5)),   # ALU→ALU on x1
    (("lw", 1, 2, None), ("add", 3, 1, 4)),  # load-use on x1
    (("add", 1, 2, 3), ("xor", 4, 5, 6)),    # independent
]
 
 
def classify(producer, consumer):
    op_p, rd_p, _, _ = producer
    op_c, _, rs1_c, rs2_c = consumer
    uses = {rs1_c, rs2_c} - {None}
    dependent = rd_p in uses
    if not dependent:
        return "none", 0, 0
    if op_p == "lw":
        # load-use: 1 stall with forwarding, 2 without
        return "stall", 1, 2
    # ALU→ALU: forward clears stalls; without forwarding need 2
    return "forward", 0, 2
 
 
actions = []
bubbles_fwd = []
bubbles_raw = []
for p, c in pairs:
    action, bf, br = classify(p, c)
    actions.append(action)
    bubbles_fwd.append(bf)
    bubbles_raw.append(br)
 
print("actions", actions)
print("bubbles with forwarding", bubbles_fwd, "total", sum(bubbles_fwd))
print("bubbles without", bubbles_raw, "total", sum(bubbles_raw))
assert actions == ["forward", "stall", "none"]
assert bubbles_fwd == [0, 1, 0]
assert sum(bubbles_fwd) == 1
assert bubbles_raw == [2, 2, 0]
assert sum(bubbles_raw) == 4
# CPI toy: ideal 1 + average stall penalty on these three
cpi_fwd = 1 + sum(bubbles_fwd) / len(pairs)
assert abs(cpi_fwd - (1 + 1 / 3)) < 1e-12
print("OK: hazard forward vs stall")
 
Самопроверка в ноутбуке
  • действия: forward / stall / none
  • пузыри с forwarding: 0+1+0=10+1+0=1
  • без forwarding: 2+2+0=42+2+0=4