(18 pt) Implement the inner product calculation of two 64-entry vectors (i.e. \(\sum_{i=0}^{63}x_i\times y_i\)).
(a) Assume \(x_i\) and \(y_i\) are signed integers (int). Write a C program to calculate their inner product. Use a loop to accumulate the products (i.e. with the loop body of "acc += x[i]*y[i];")
(b) Assume \(x_i\) is {1, −2, 3, −4, 5, −6, …, −62, 63, −64}, where odd numbers are positive and even numbers are negative. Find the binary representations (2's complement) of \(x_0\), \(x_1\), \(x_2\), and \(x_3\) respectively.
(c) The leading bits of the binary representations for small numbers (such as those in \(x_i\) in (b)) are all sign bits (i.e. 0's for positive and 1's for negative). Therefore, the inner product calculation of (b) will have significant bit transitions (due to the alternated signs) and thus consume large power. Someone unrolled the loop body in (a) as
acc += x[2*j]*y[2*j]; acc -= x[2*j+1]*y[2*j+1];
with all-positive \(x_i\) = {1, 2, 3, 4, 5, 6, …, 62, 63, 64} to reduce bit transitions (i.e. the leading sign bits are all zeroes now), but found it did not actually save power for some processors (also with a single hardware multiplier only). List two possible reasons.
(d) An alternative to implement the low-power inner product in (c) is to use two separate loops: one for "acc += x[2*j]*y[2*j];" and the other for "acc -= x[2*j+1]*y[2*j+1];". Can this approach help to save power? Briefly explain your answer.
(a)
int inner_product(const int x[64], const int y[64]) {
int acc = 0;
for (int i = 0; i < 64; i++)
acc += x[i] * y[i];
return acc;
}
(b) int 是 32 bit:
| 值 | 2's complement | hex | |
|---|---|---|---|
| \(x_0\) | 1 | 0000 0000 0000 0000 0000 0000 0000 0001 | 0x00000001 |
| \(x_1\) | −2 | 1111 1111 1111 1111 1111 1111 1111 1110 | 0xFFFFFFFE |
| \(x_2\) | 3 | 0000 0000 0000 0000 0000 0000 0000 0011 | 0x00000003 |
| \(x_3\) | −4 | 1111 1111 1111 1111 1111 1111 1111 1100 | 0xFFFFFFFC |
只看低 8 bit:0000 0001、1111 1110、0000 0011、1111 1100。正負交替,前面約 30 個 sign bit 每次都整排翻轉
(c) 兩個可能的原因:
① acc -= p 在硬體上是 acc + (~p + 1),adder 實際收到的是 product 的 2's complement,又是一整排 leading 1;+= 與 -= 交替,adder 輸入的高位元照樣每次整排翻轉,transition 只是從 multiplier 輸入搬到 adder 輸入
② 只把 \(x_i\) 改成全正,\(y_i\) 的正負沒變,product 的 sign 與高位元仍會交替;而且處理器的功耗大部分在 instruction fetch、register file、memory access 與 loop control,這些都沒變(交替的 add/sub 指令還會讓指令位元與 ALU 控制訊號翻轉),multiplier 輸入少掉的那點 transition 被蓋掉
(d) 可以。第一個 loop 全是 +=、第二個 loop 全是 -=:同一個 loop 內 adder 做的運算固定,送進 adder 的運算元高位元都是同一種 sign bit,前後兩次迭代之間不再整排翻轉,只有兩個 loop 交界翻一次
代價是多一個 loop 的 overhead,且 x、y 要各掃兩次;前提是 \(y_i\) 本身的正負不會交替,否則 product 的 sign 還是會翻
(b) 0x00000001、0xFFFFFFFE、0x00000003、0xFFFFFFFC (d) 可以(運算固定、不交替 add/sub)