Yu-Ti Kuo
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Assignment 1: RISC-V Assembly and Instruction Pipeline contributed by < [`eastwillow`](https://github.com/eastWillow) > You can find the source code [here](https://github.com/eastWillow/ca2025-quizzes). Feel free to fork and modify it. Chinese Version and Previous History: [作業一:RISC-V 組合語言與指令管線](/19zTeKL2QwGOZdmL62_o0g) **Acknowledgment of AI Usage**: All use of AI tools has been documented transparently. The ChatGPT conversation link will be attached at the end of this assignment. [Here](#AI-Disclosure) > All use of AI tools must be transparent and appropriately documented. [^Guidelines_of_AI] ## Problem-solving steps 0. Understand the assignment requirements; the assignment statement says you can use real-world applications to focus the content. 1. Understand the RISC-V Unprivileged specification — here I place some parts that are used while writing the assignment. 2. Understand the behavior of the RISC-V 5-Stage Pipeline. 3. Understand the RISC-V emulator: RIPES environment. 4. Break the big problems into smaller ones, first write drafts in the familiar C language. 5. Use AI and mathematical formulas to generate test data; try to achieve 100% line coverage. 6. For program behaviors that have been fixed, refactor step-by-step — convert the C language program gradually into RV32I assembly; finish the problem first. 7. Compare performance differences between C and handwritten assembly using realistic code examples most commonly used in real problems. ## Use a real-world application to focus the assignment > Develop a simplified but informative use case to frame your assignment. You may select examples from LeetCode or practical open-source projects related to the quiz problems. For instance: [^assignment1Request] ### Problem B [^arch2025-quiz1-sol#Problem-B] applied to ultrasonic distance sensor error estimation > Assume uf8 implements a logarithmic 8-bit codec that maps 20-bit unsigned integers ([0,1,015,792]) to 8-bit symbols via logarithmic quantization, delivering 2.5:1 compression and ≤6.25% relative error. > The uf8 encoding scheme is ideal for sensor data applications such as temperature and distance measurements where range is more important than precision. In graphics applications, it efficiently represents level-of-detail (LOD) distances and fog density values. The scheme is also well-suited for timer implementations that use exponential backoff strategies. However, the uf8 encoding should not be used for financial calculations where exact precision is required and rounding errors are unacceptable. It is inappropriate for cryptographic applications that require uniform distribution of values for security purposes. Error Analysis * Absolute Error: $\Delta_{\max} = 2^e - 1$ * Relative Error: $\varepsilon_{\max} = 1/16 = 6.25%$ * Expected Error: $\mathbb{E}[\varepsilon] \approx 3%$ Assume a real-world application uses an ultrasonic sensor-equipped robot and records measured distances. Distance unit: millimeter (mm) Sensor true output range: 20 mm ~ 4000 mm (4 m) Compare these numeric formats directly by their "semantic value range" to get an intuitive understanding of what distance intervals they can represent. | format | space | distance range (mm) | | --------------------- | ------: | ---------------------------------- | | **uint8_t** | 1 byte | $0 \sim 255\ \text{mm}$ | | **float (IEEE754)** | 4 bytes | $\pm 3.4 \times 10^{38} \text{mm}$ | | **uf8 (logarithmic)** | 1 byte | $0 \sim 1,015,792\ \text{mm}$ | Then, to avoid wasting those maximum ranges, you can use scaling; for example, scale 0 ~ 4000 mm into the represented range so uint8_t increases maximum distance, and uf8 improves precision. | format | each step | | ------ | ------------------------------------------------ | | uin8_t | $\frac{4000}{255} \approx 15.69 \text{ mm}$ | | float | error is variable; at 15 mm roughly 1.8e-6 mm | | float | error is variable; at 4000 mm roughly 0.238 mm | | uf8 | error is variable; at 15 mm roughly 0.00394 mm | | uf8 | error is variable; at 4000 mm roughly 12.90 cm | $$ \text{scale factor} = \frac{4000}{1{,}015{,}792} \approx 0.003937814041 $$ | Exponent | Range | Scaling 4000 mm | Step Size | | -------- | ---------------------------- | ---------------- | ------------------------------- | | 0 | $[0, 15]$ | $[0, 0.059]$ | 0.00394 mm | | 1 | $[16, 46]$ | $[0.063, 0.181]$ | 0.07875 mm | | 2 | $[48, 108]$ | $[0.189, 0.425]$ | 0.01575 mm | | 3 | $[112, 232]$ | $[0.441, 0.914]$ | 0.03150 mm | | ... | ... | ... | $2^e \cdot \text{scale factor}$ | | 15 | $[524{,}272, 1{,}015{,}792]$ | $[2065, 4000]$ | 12.9034 cm | ### Problem C [^arch2025-quiz1-sol#Problem-C] #### float32 <-> bfloat16 bit mapping and introduction $$ v = (-1)^S \times 2^{E-127} \times \left(1 + \frac{M}{128}\right) $$ $S \in {0, 1}$ is the sign bit $E \in [1, 254]$ is the biased exponent $M \in [0, 127]$ is the mantissa value ``` Float32 (32 bits) ┌──────────┬──────────────┬───────────────────────────────┐ │ Sign (1) │ Exponent (8) │ Mantissa (23 bits) │ └──────────┴──────────────┴───────────────────────────────┘ 31 30 23 22 16 0 │ │ │ │ │ │ │ │ │ │ ▼ ▼ ▼ ▼ ▼ ┌──────────┬──────────────┬──────────────┐ │ Sign (1) │ Exponent (8) │ Mantissa (7) │ ← Keep the high 16 bits └──────────┴──────────────┴──────────────┘ 15 14 7 6 0 ``` Here’s how you can extend your `bf16_t` structure with a union so it can be accessed both as a raw 16-bit value and as individual bit fields (sign, exp, mantissa): [Disscuss with AI](https://chatgpt.com/share/68efb967-b498-8003-9e1e-982e89720076) ```cpp #include <stdint.h> typedef union { uint16_t bits; struct { #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ uint16_t mantissa : 7; // M: Fraction bits uint16_t exponent : 8; // E: Exponent bits (bias = 127) uint16_t sign : 1; // S: Sign bit (0 = positive, 1 = negative) #else uint16_t sign : 1; uint16_t exponent : 8; uint16_t mantissa : 7; #endif } f; } bf16_t; ``` You can verify what your compiler defines: [^gccEngian] ```bash gcc -dM -E - < /dev/null | grep ENDIAN ``` Oh My Computer `gcc (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0` ```cpp #define __ORDER_LITTLE_ENDIAN__ 1234 #define __FLOAT_WORD_ORDER__ __ORDER_LITTLE_ENDIAN__ #define __ORDER_PDP_ENDIAN__ 3412 #define __ORDER_BIG_ENDIAN__ 4321 #define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__ ``` #### A quick exploration of different C expressions to obtain the sign bit and performance differences | Expression | RV32I cost | Notes | | --------------------------- | ---------- | ----------------------------------------------------------------- | | `a.f.sign` | ~3 inst | may involve bitfield layout logic; not always inlined predictably | | `(b.bits >> 15) & 1` | ~3 inst | always explicit and portable | | `bool sign = b.bits >> 15;` | ~2 inst | mask implicit; works since shift already leaves 0/1 | ![image](https://hackmd.io/_uploads/H1sDw31pll.png) #### Steps to convert float32 -> bfloat16 1. Sign & Exponent bits remain. 2. float32 follows the IEEE-754 spec *round to nearest, ties to even* Extract the low 16 bits to be discarded: ```c 0x0000FFFF + 0x7FFF ``` (0x7FFF = 0111 1111 1111 1111) This is equivalent to adding "0.5" to implement rounding (because 0x7FFF ≈ half). ```c + ((f32bits >> 16) & 1) ``` This step is the key to ties-to-even. When the discarded portion equals exactly `0x8000` (that is, exactly half), if the last kept bit is odd, round up; if even, do not round up. This makes the result conform to IEEE's "ties-to-even" rule (avoids statistical bias). Finally shift right by 16 bits. Complete round-to-nearest-even. See Section 4.3 — Rounding-direction attributes [^IEEE-754_2019] #### BF16 preserves exponent to express large dynamic range, but dropped precision can be useful in certain domains Reducing 32 bits to 16 bits was used by Google in LLMs to keep exponent while discarding precision; this format discards precision in a way that can be acceptable in physical sensor applications where sensor intrinsic precision does not require full float32 precision (for example some temperature sensors). It’s suited for domains with large dynamic range but tolerant to precision loss, such as temperature gauges, audio-level meters, etc. It can save storage space when sensor precision (like DHT11) cannot take advantage of full float32 precision. #### Actual precision of temperature/humidity sensors | Sensor | Temperature resolution | Temperature error | Humidity resolution | Humidity error | | ------------------------- | :--------------------: | :---------------: | :-----------------: | :------------: | | **DHT11**[^DHT11] | 1 °C | ±2 °C | 1 %RH | ±5 %RH | | **DHT22/AM2302**[^AM2302] | 0.1 °C | ±0.5 °C | 0.1 %RH | ±2 %RH | | **SHT31**[^SHT31] | 0.015 °C | ±0.3 °C | 0.01 %RH | ±2 %RH | #### Can bfloat16 per-step values represent sensor precision? bfloat16 precision at different numeric ranges: $$ \text{step} = \text{value} \times \frac{1}{128} \approx 0.78 \% $$ ##### Temperature precision | Actual value | 1 ULP size (approx) | Meaning | | ------------ | ------------------: | ---------------------------- | | 20 °C | 0.156 °C | Can represent ~0.16 °C steps | | 50 °C | 0.39 °C | ~±0.4 °C | | 100 °C | 0.78 °C | ~±0.8 °C | ##### Humidity precision | Humidity | 1 ULP size (approx) | | -------- | ----------------------------: | | 50 %RH | $(50 \cdot 0.78\%) = 0.39$ %RH | | 100 %RH | 0.78 %RH | #### Conclusion table | Sensor | Sensor error | bfloat16 error | Will it cause precision loss? | | ------ | ---------------- | ------------------- | ---------------------------------- | | DHT11 | ±2 °C / ±5 %RH | ±0.16 °C / ±0.4 %RH | ❌ No | | DHT22 | ±0.5 °C / ±2 %RH | ±0.16 °C / ±0.4 %RH | ❌ No | | SHT31 | ±0.3 °C / ±2 %RH | ±0.16 °C / ±0.4 %RH | ⚠️ Might slightly lose, acceptable | ## Understand the RISC-V Unprivileged spec — special notes when writing the assignment ### pseudoinstructions Assembly will replace pseudoinstructions[^listing-of-standard-risc-v-pseudoinstructions] to RISC-V instructions. Someone has summarized common pseudoinstruction expansions: [riscv-card](https://github.com/jameslzhu/riscv-card) Examples: 1. `mv rd, rs` is actually `addi rd, rs, 0` (rd = rs + 0). [^RISCVUnprivileged] 2. `nop` by spec is `addi x0, x0, 0`. [^RISCVUnprivileged] There are also some not defined in the Spec [^RISCVUnprivileged]. `li rd, imm` Observe Ripes’s expansion will produce different RV32I instructions depending on `imm` size. E.g., when imm fits in I-type addi imm[11:0], it expands to `addi rd, x0, imm`. ### Stack Pointer Use `sp` (stack pointer) to store the stack; memory grows downward from 0xFFFFFFFF. We can use the stack pointer to save variables for a function’s caller. Note: In the standard RISC-V calling convention, the stack grows downward and the stack pointer is always kept 16-byte aligned. [^RISCV32_CALLING] ### Logical Shift vs. Arithmetic Shift Be careful of the (logical shift) vs (arithmetic shift) [^c-bitwise]. GCC’s implementation on RISC-V aligns with this specification by performing arithmetic right shifts on signed integers. [^gccIntegers-implementation] `lbu` & `lb` are different. `lb` will sign extend (0xF0 -> 0xFFFF FFF0) `lbu` will keep the sign (0xF0 -> 0x0000 00F0) In the problem’s C code there is a use of `int32_t` for `new_exp >>= 1`; here the behavior differs. Use `srai` (arithmetic right shift) to match C behavior: `srai s8, s8, 1 # new_exp >>= 1` [bf16_sqrt.c#L65](https://github.com/eastWillow/ca2025-quizzes/blob/db3ee12b4ad4cd8a03ee1f2742354d2cf9b8da11/q1-bfloat16/bf16_sqrt.c#L65) ```c int32_t new_exp; /* Get full mantissa with implicit 1 */ mant = 0x80 | mant; /* Range [128, 256) representing [1.0, 2.0) */ /* Adjust for odd exponents: sqrt(2^odd * m) = 2^((odd-1)/2) * sqrt(2*m) */ int32_t mask = (e & 1); mant <<= mask; /* Double mantissa for odd exponent */ new_exp = ((e - mask) >> 1) + BF16_EXP_BIAS; ``` ## RISC-V Single-Cycle behavior ![image](https://hackmd.io/_uploads/BJE59gt6gl.png) I have already taken an online course to implement a basic RISC-V Single Core yourself [^LFD111x] [My HDL source code for each chapter of that course](https://drive.google.com/drive/folders/1LaKL7PigLCAuZSS0Fhs8ON_9FQ7pY5W9?usp=sharing) [Certificate obtained after passing the course](https://courses.edx.org/certificates/149d377201e74e3fbd4d9b192c9d73bc) ## RISC-V 5-Stage Pipeline behavior ### Introduction: differences between 5-stage pipelined processor and single-cycle processor The main idea is splitting the Single Cycle Processor’s Fetch, Decode opcode, Execute or Memory Load/Store, Write Back into 5 stages. For example, while fetching an instruction you can simultaneously decode the opcode because those two actions' order does not affect other instructions. In an optimal clock, the pipeline will be filled with 5 instructions to execute. ![image](https://hackmd.io/_uploads/SJPDGZY6lg.png) Ripes also provides performance metrics in the bottom-right. [FromAI](https://chatgpt.com/share/68efbaac-909c-8003-a9bb-1eb8e18b42e2) | Parameter | Full name | Meaning | Explanation | | ------------------- | ---------------------- | ------------------------------ | ----------------------------------------------------------------------------------------- | | **Cycles** | Clock Cycles | Total execution cycles | Total clock cycles used to execute this program. Smaller is faster. | | **Instrs. retired** | Instructions Retired | Completed instruction count | Number of instructions completed and retired. | | **CPI** | Cycles Per Instruction | Average cycles per instruction | `CPI = Cycles / Instructions`. Smaller is better. | | **IPC** | Instructions Per Cycle | Average instructions per cycle | `IPC = 1 / CPI`. Larger is better. | | **Clock rate** | Frequency | Clock frequency | Simulator typically shows 0 Hz (no physical clock specified). If known, can compute time. | CPI is 5 when a single instruction needs 5 clocks because the pipeline is not yet filled. Ideally, CPI approaches 1 for maximum pipelining efficiency. However, since RIPES may not model additional cycles caused by peripherals and other real-world effects, the absolute CPI comparison between a 5-stage pipeline and a single-cycle RV32I processor should be interpreted with caution. In reality memory operations may require additional cycles for store/load; while waiting for store/load, you can fetch following instructions to show pipelined benefits. ### Demonstrate each stage: IF, ID, EX, MEM, WB | Stage | Abbreviation | Major Hardware Used | | ------------------ | -------------- | ------------------------------------------------ | | Instruction Fetch | **IF** | Program Counter (PC), Instruction Memory | | Instruction Decode | **ID** | Register File, Control Unit, Immediate Generator | | Execute | **EX (or IE)** | ALU, Branch Unit | | Memory Access | **MEM** | Data Memory | | Write Back | **WB** | Register File | | Stage | Full Name | Abbrev. | Function | Example (`ADD x3, x1, x2`) | | ----- | ------------------ | ------- | -------------------------------------------- | ------------------------------------- | | **1** | Instruction Fetch | **IF** | Fetch the instruction and update PC | Fetch `ADD x3, x1, x2`; `PC = PC + 4` | | **2** | Instruction Decode | **ID** | Decode instruction and read registers | Decode as R-type; read `x1`, `x2` | | **3** | Execute | **EX** | Perform ALU operation or address calculation | `x1 + x2` → ALU result | | **4** | Memory Access | **MEM** | Access data memory | No action for `ADD`; `LW` reads data | | **5** | Write Back | **WB** | Write result back to register file | Write result to `x3` | ![image](https://hackmd.io/_uploads/ByswqxYTgx.png) Pipeline Hazards: 1. Structural Hazard 2. Data Hazard / Memory hazard 3. Control Hazard / Branch Hazard Branches create hazards — pipeline bubbles — so prefer branch-less approaches to reduce these and improve CPI. This will increase CPI otherwise. Later you can use CPI comparison to prove improvements. Keep this in mind when writing RV32I ASM. Afater the Due Day, I read the classmate assignemt to learn. {%preview https://hackmd.io/@phyrexxxxx/arch2025-homework1 %} {%preview https://hackmd.io/@ukp66482/arch2025-homework1 %} {%preview https://hackmd.io/@jJPXUgTOQFa2Lhe0rEbtQg/Arch2025-homework1 %} {%preview https://hackmd.io/@kaihsiangyang/arch2025-homework1 %} {%preview https://hackmd.io/@ChouAn/arch2025-homework1 %} Notice the Harazd and imprvoe the asm. New Method {%preview https://hackmd.io/@winterchen/arch2025-homework1 %} ## RISC-V Emulator: Ripes environment introduction Because RISC-V provides the execution environment[^RISCVUnprivileged], we can use Ripes `ecalls`[^RipesEcalls] to print strings. > The implementation of a RISC-V execution environment can be pure hardware, pure software, or a combination of hardware and software. For example, opcode traps and software emulation can be used to implement functionality not provided in hardware. Currently used ecalls in writing the assignment: #### system exit return 0 ```c li a7, 10 ecall ``` #### print string ```c .data correct_str: .string "correct\n" .text la a0, correct_str li a7, 4 ecall ``` #### print hex ```c .data printed_hex: .word 0x1234 .text la s0, printed_hex # input pointer lw a0, 0(s0) # load input element li a7, 34 ecall ``` ## Break the big problems into smaller ones, first write drafts in C Coding Format follows `rv32emu contributing-ov-file`[^rv32emu] Use math formulas, specs, AI to generate test data; aim for 100% line coverage Use `gcov + lcov` to produce coverage reports to confirm each line is executed ### Test cases for uf8_decode in Problem B [uf8_decode.c#L18](https://github.com/eastWillow/ca2025-quizzes/blob/db3ee12b4ad4cd8a03ee1f2742354d2cf9b8da11/q1-uf8/uf8_decode.c#L18) ``` uf8 test_values[] = {0x00, 0x01, 0x0F, 0x10, 0x1F, 0x20, 0x2F, 0x30, 0x3F, 0xF0, 0xFF}; uint32_t expect_values[] = {0, 1, 15, 16, 46, 48, 108, 112, 232, 524272, 1015792}; ``` ### Test cases for f32_to_bf16 in Problem C Positive and negative infinity (inf, -inf) Positive and negative zero (0.0, -0.0) NaN Exactly representable values (e.g., 1.0, 0.5) Values requiring rounding (e.g., 1.00097656f, 1.00048828f) Designing f32_to_bf16 test cases must consider: 1. Check the bits being discarded [15:0]; 2. If greater than 0x8000 → round up; 3. If equal to 0x8000 and the kept bit [16] is 1 → round up; 4. Otherwise do not round up. ```cpp f32bits += ((f32bits >> 16) & 1) + 0x7FFF; // [16] + [15:0] > 0x8000 return (bf16_t){.bits = f32bits >> 16}; ``` ### Test cases for bf16_add and bf16_sub in Problem C Found a class of test behavior requiring reference to IEEE-754: > When the sum of two operands with opposite signs (or the difference of two operands with like signs) is exactly zero, the sign of that sum (or difference) shall be +0 under all rounding-direction attributes except **roundTowardNegative**; under that attribute, the sign of an exact zero sum (or difference) shall be −0. However, under all rounding-direction attributes, when x is zero, x+x and x−(−x) have the sign of x. [^IEEE-754_2019] | Expression | Result sign | Explanation | | ------------- | ----------: | ----------------------------: | | `(+0) + (+0)` | `+0` | same sign addition keeps sign | | `(-0) + (-0)` | `-0` | same sign addition keeps sign | | `(+0) + (-0)` | `+0` | shall be +0 | | `(-0) + (+0)` | `+0` | shall be +0 | | `(+0) - (+0)` | `+0` | same as `(+0) + (-0)` | | `(-0) - (-0)` | `+0` | same as `(-0) + (+0)` | | `(+0) - (-0)` | `+0` | same as `(+0) + (+0)` | | `(-0) - (+0)` | `-0` | same as `(-0) + (-0)` | We must confirm the gcc rv32 implementation. After experiments, float32 default is roundTiesToEven: ``` gcc bf16_add.c -o bf16_add.o -lm && ./bf16_add.o ``` Results showed bf16 implementation needs fixing for zero subtraction; may need to submit a pull request. [commit/e0ae7a](https://github.com/eastWillow/ca2025-quizzes/commit/e0ae7a90a350a3ebcc196e26ff707765ed8f780d?w=1) Confirm bf16 behavior aligns to f32 before translating to ASM: [commit/9aec45](https://github.com/eastWillow/ca2025-quizzes/commit/9aec4505bc15d05b40baa72b6be607b5aac182c1) ```bash Now Test: 0 bf16_add: 0x0 bf16_sub: 0x8000 f32_add: +0.000000 f32_sub: +0.000000 ``` ### For bf16_sqrt in Problem C, found parts of the C code may remain in C and still keep consistent behavior While designing tests for bf16_sqrt found current results will not exceed 256. [q1-bfloat16.c#L323C46-L323C49](https://github.com/eastWillow/ca2025-quizzes/blob/db3ee12b4ad4cd8a03ee1f2742354d2cf9b8da11/q1-bfloat16.c#L323C46-L323C49) ```c uint32_t m = 0x80 | mant; /* Range [128, 256) representing [1.0, 2.0) */ ``` For example 0x2222 -> 0x4444; mantissa grows toward upper bound 256, but won't reach it. Because the m is in Range `[128, 256)` ## Using fixed program behavior, gradually refactor into RV32I ASM ### Example: bfloat16_mul in Problem C #### Multiplication must be converted into ASM using only RV32I instructions ```c uint32_t result_mant = (uint32_t) mant_a * mant_b; ``` #### Step1 convert to loop multiplication [q1-bfloat16.c#L190](https://github.com/eastWillow/ca2025-quizzes/blob/db3ee12b4ad4cd8a03ee1f2742354d2cf9b8da11/q1-bfloat16.c#L190) ```c static inline uint32_t mul(uint32_t a, uint32_t b) { uint32_t result_mant = 0; for (int i = 0; i < 32; i++) { if (b & (1 << i)) result_mant += a << i; } return result_mant; } ``` ```diff - uint32_t result_mant = (uint32_t) mant_a * mant_b; + uint32_t result_mant = mul(mant_a, mant_b); ``` #### Step2 replace the inline function ```diff - uint32_t result_mant = mul(mant_a, mant_b); + uint32_t result_mant = 0; + for (int i = 0; i < 32; i++) { + if (mant_b & (1 << i)) + result_mant += mant_a << i; + } ``` #### Done : Replace the `if` statement with a bitwise expression [bf16_mul.c#L74](https://github.com/eastWillow/ca2025-quizzes/blob/db3ee12b4ad4cd8a03ee1f2742354d2cf9b8da11/q1-bfloat16/bf16_mul.c#L74) ```diff - if (mant_b & (1 << i)) - result_mant += mant_a << i; + uint32_t mask = -((mant_b >> i) & 1); + // bit=1 , mask=0xFFFFFFFF + // bit=0 , mask=0x00000000 + result_mant += (mant_a << i) & mask; ``` ### For bfloat16_sqrt in Problem C you also need to replace the multiplication ```diff - uint32_t sq = (mid * mid) / 128; /* Square and scale */ + uint32_t sq = 0; + for (int i = 0; i < 32; i++) { + uint32_t mask = -((mid >> i) & 1); + // bit=1 , mask=0xFFFFFFFF + // bit=0 , mask=0x00000000 + sq += (mid << i) & mask; + } + sq = sq >> 7; ``` ### In Problem C bfloat16_div Replace the `if` statement with a bitwise expression ```diff @@ -60,11 +60,15 @@ static inline bf16_t bf16_div(bf16_t a, bf16_t b) uint32_t divisor = mant_b; uint32_t quotient = 0; + uint32_t mask = 0; + uint32_t shifted_divisor = 0; for (int i = 0; i < 16; i++) { quotient <<= 1; - if (dividend >= (divisor << (15 - i))) { - dividend -= (divisor << (15 - i)); - quotient |= 1; - } + shifted_divisor = (divisor << (15 - i)); + mask = (dividend < shifted_divisor); + mask = mask ^ 1; + mask = -mask; + dividend -= (shifted_divisor) &mask; + quotient |= 1 & mask; } ``` ### In Problem C bfloat16_comp(eq/lt/gt): Replace greater-than comparisons with equivalent less-than forms Because RV32I only has set-less-than instruction: [^RISCVUnprivileged] `slt rd, rs1, rs2` `rd = (rs1 < rs2)?1:0` ```diff @@ -66,7 +66,7 @@ static inline bool bf16_lt(bf16_t a, bf16_t b) // a < b uint32_t sign_b = (b.bits >> 15) & 1; // s7 if (sign_a != sign_b) - return sign_a > sign_b; + return sign_b < sign_a; - return sign_a ? a.bits > b.bits : a.bits < b.bits; + return sign_a ? b.bits < a.bits : a.bits < b.bits; } ``` ### Share writing process tips ![image](https://hackmd.io/_uploads/SkAi2SU6gx.png) A recommended method when writing ASM is to create a Variable Register Map to manage the manual lifecycle. This helps debug and confirm register values are correct. ![image](https://hackmd.io/_uploads/SkxGLyualx.png) ## Performance differences between C and handwritten assembly — use common real-world code as example For Problem B the most-used operation expected is CLZ; isolate CLZ to compare differences. I designed full-coverage tests to ensure different implementations produce the same final result. [q1-uf8/clz.c](https://github.com/eastWillow/ca2025-quizzes/blob/main/q1-uf8/clz.c) ```bash Overall coverage rate: lines......: 100.0% (44 of 44 lines) functions......: 100.0% (3 of 3 functions) ``` ### Code size differences — compiled binary size comparison Use Ripes instruction memory as code size. Ripes RISC-V Compiler Setting: ![Ripes RISC-V Compiler Setting](https://hackmd.io/_uploads/rJ3EuVKTgl.png) RISC-V C Compiler Install Manual: [Lab2: RISC-V `RV32I[MA]` emulator with ELF support](https://hackmd.io/3tO0gfoqT7upOzVpFZlFBw) **Problem B: binary-search loop style clz is smallest** [**ASM** Bitwise style clz](https://github.com/eastWillow/ca2025-quizzes/blob/main/q1-uf8/clz.s) Code Size : 0x100 ![image](https://hackmd.io/_uploads/BJ2w3zKpll.png) [**ASM** binary-search loop style clz](https://github.com/eastWillow/ca2025-quizzes/blob/main/q1-uf8/loop_clz.s) Code Size : 0x9C ![image](https://hackmd.io/_uploads/HkO3YftTge.png) [**C Code** binary-search loop style clz](https://github.com/eastWillow/ca2025-quizzes/blob/main/q1-uf8/clz_loop.c) Code size : 0x21C58 - 0x100b4 = 0x11BA4 ![image](https://hackmd.io/_uploads/B1nzhMK6ex.png) ![image](https://hackmd.io/_uploads/BJ_Xnft6gx.png) ### Performance differences, using Ripes metrics for comparison Compare CPI to see which is closer to 1 (better). Under Ripes constraints, use the same processor to compare. The following uses a 5-stage pipelined processor. #### Problem B: bitwise style clz performs best [Bitwise style clz](https://github.com/eastWillow/ca2025-quizzes/blob/main/q1-uf8/clz.s) ![image](https://hackmd.io/_uploads/Bk1QrGY6xg.png) [binary-search loop style clz](https://github.com/eastWillow/ca2025-quizzes/blob/main/q1-uf8/loop_clz.s) ![image](https://hackmd.io/_uploads/Hy4t8MYagl.png) ### Memory usage differences — in practice sensors need storage for recording 1. uf8 consumes 1 Byte 2. bf16 consumes 2 Bytes 3. float (IEEE-754) consumes 4 Bytes ## AI Disclosure I Use Free Chat GPT Plan. ![image](https://hackmd.io/_uploads/SJzXuN66xl.png) 1. Learning RV32I ASM Coding [Link](https://chatgpt.com/share/68efb767-cc78-8003-8986-5cc599a7d067) 2. Using RIPES Simulator [Ripes Ecall Example](https://chatgpt.com/share/68efb7aa-9778-8003-9845-c3de1abeef6d) 3. CLZ Performance Analysis and Validation [CLZ Performance Improve](https://chatgpt.com/share/68efb8a6-6c70-8003-b8fd-375562001e62) 4. RV32I ASM Array Best Practices [RV32I ASM Array](https://chatgpt.com/share/68efb8fa-8f08-8003-8801-26d56d62aeec) 5. Replacing Branches with Bitwise Masks [Bitwise Mask Replace Branch](https://chatgpt.com/share/68efb9aa-0b14-8003-9c94-41433be2675c) 6. BF16 and Float32 Conversion, Floating-Point Spec, and ASCII Visualization [Link](https://chatgpt.com/share/68efba12-0648-8003-a3da-7dcbb3e5c7d7) 7. Brainstorming with AI to Calculate Real-World and Floating-Point Step Errors [Link](https://chatgpt.com/share/68efba71-91c0-8003-80ae-954d9bd65262) 8. Performance Metrics in RIPES [Link](https://chatgpt.com/share/68efbaac-909c-8003-a9bb-1eb8e18b42e2) 9. Planning Register Maps and Exploring IEEE-754 Addition Spec [Link](https://chatgpt.com/share/68efbb05-89f0-8003-ac04-8325f2e87bb3) [^assignment1Request]: [Assignment1: RISC-V Assembly and Instruction Pipeline](https://hackmd.io/@sysprog/2025-arch-homework1) [^arch2025-quiz1-sol#Problem-B]: [Quiz1 of Computer Architecture (2025 Fall)](https://hackmd.io/@sysprog/arch2025-quiz1-sol#Problem-B) [^arch2025-quiz1-sol#Problem-C]: [Quiz1 of Computer Architecture (2025 Fall)](https://hackmd.io/@sysprog/arch2025-quiz1-sol#Problem-C) [^listing-of-standard-risc-v-pseudoinstructions]: [a-listing-of-standard-risc-v-pseudoinstructions](https://github.com/riscv-non-isa/riscv-asm-manual/blob/e1779658b82451b34e36207042f06bce8f25a034/src/asm-manual.adoc#a-listing-of-standard-risc-v-pseudoinstructions) [^RipesEcalls]: [Ripes ecalls.md](https://github.com/mortbopet/Ripes/blob/master/docs/ecalls.md) [^RISCVUnprivileged]: [RISC-V+Technical+Specifications](https://riscv.atlassian.net/wiki/spaces/HOME/pages/16154769/RISC-V+Technical+Specifications) [^rv32emu]: [rv32emu contributing-ov-file](https://github.com/sysprog21/rv32emu?tab=contributing-ov-file) [^c-bitwise]: [The C language you don't know: bitwise operations](https://hackmd.io/@sysprog/c-bitwise) [^gccIntegers-implementation]: [gcc-Integers-implementation](https://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html#Integers-implementation) [^gccEngian]: [gcc-Common-Predefined-Macros](https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html) [^IEEE-754_2019]: [IEEE-754_2019 on IEEE](https://doi.org/10.1109/IEEESTD.2019.8766229) or [IEEE-754 2019 pdf on web](https://www-users.cse.umn.edu/~vinals/tspot_files/phys4041/2020/IEEE%20Standard%20754-2019.pdf) [^RISCV32_CALLING]: [riscv-calling.pdf](https://riscv.org/wp-content/uploads/2024/12/riscv-calling.pdf) [^DHT11]: [DHT11 Datasheet pdf](https://www.mouser.com/datasheet/2/758/DHT11-Technical-Data-Sheet-Translated-Version-1143054.pdf) [^AM2302]: [AM2302 Datasheet pdf](https://cdn.sparkfun.com/assets/f/7/d/9/c/DHT22.pdf) [^SHT31]: [SHT31 Datasheet pdf](https://www.mouser.com/datasheet/2/682/Sensirion_Humidity_SHT3x_Datasheet_analog-767292.pdf) [^LFD111x]: [building-a-riscv-cpu-core-lfd111x](https://training.linuxfoundation.org/training/building-a-riscv-cpu-core-lfd111x/) [^Guidelines_of_AI]: [Computer Architecture (2025 Fall): Guidelines for Student Use of AI Tools](https://hackmd.io/@sysprog/arch2025-ai-guidelines)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully