The 5,404 daily SPY returns fill 675 registers of 8 lanes and leave 4 numbers over. Drop those four and the last days of your sum are missing; read past the end and you read somebody else's memory. How do you finish the job, and what does it cost?
The idea in plain words
Where we are. Every kernel so far refused an array whose length was not a multiple of the lane count, and the C version of the last topic simply said "n is a multiple of 4" in a comment. Real data does not oblige. This topic builds the two pieces that make a vector loop usable on any array: handling the tail, and starting from an aligned address.
Any array splits into three parts: a short head of single elements until the address is aligned, a body of whole registers, and a short tail of single elements. Only the body runs on vector instructions.
Both ends are handled with the scalar instructions you already have, which is why the loops are slower there but still correct. The head and the tail are short, fewer than lanes elements each, so for a long array they are a tiny share of the work. For a short array they can be most of it, and that is a reason to measure before vectorizing.
The smallest example: two ways to get the tail wrong
Take 7 numbers on 4 lanes: one full register and 3 left over. The first mistake is to loop only over the full registers and say nothing about the rest. Nothing fails: the output has 7 slots and the last three keep their starting zeros.
# Mistake 1: loop over the full registers only. The last 3 sums are simply never computeda = [float(i) for i in range(7)]b = [1.0] * 7sim = LaneSim(4)out = [0.0] * 7for i in range(0, 7 - 7 % 4, 4):1 sim.vstore(out, i, sim.vadd(sim.vload(a, i), sim.vload(b, i)))print(out)
[1.0, 2.0, 3.0, 4.0, 0.0, 0.0, 0.0]
- 1
7 - 7 % 4is 4: only one register fits.
The second mistake is the opposite: round the loop up and load the last, partly empty register. LaneSim refuses with a ValueError. Real hardware does not: a load simply reads the next four numbers in memory, whatever they are, and may stop the program if that memory belongs to nobody. The simulator is strict on purpose so you notice.
# Mistake 2: load the last, partly empty registersim = LaneSim(4)sim.vload(a, 4)
ValueError: vector load out of range
Build it up: peel, body and tail
Alignment first. A register of 4 numbers of 8 bytes is 32 bytes wide, and an array is aligned for it when its first element sits at a byte address that is a multiple of 32. is_aligned is that test. The array's own start is usually aligned by the allocator, but a slice such as returns[1:] starts one element, 8 bytes, later and no longer is. peel_count says how many single elements to handle until the next one is aligned.
# Where an array that starts at this byte address becomes aligned for 4 lanes of 8 bytes (32 bytes wide)for address in (0, 8, 16, 24, 32, 40, 4104): print(address, is_aligned(address, 32), peel_count(address, 4))1
0 True 0 8 False 3 16 False 2 24 False 1 32 True 0 40 False 3 4104 False 3
- 1The peel is 3 at address 8, 2 at 16, 1 at 24, and 0 once aligned.
- 1PeelHandle single elements from the front until the address is aligned.
- 2Run the bodyProcess whole registers, one vector pass per
laneselements. - 3Finish the tailHandle the last few elements one at a time. Never read past the end.
split_work turns an array length and a start address into the three counts. Try the lengths of the lead: 5,404 returns starting aligned give no head, 5,400 in the body and 4 in the tail on 8 lanes, while a slice that starts 8 bytes later gives a head of 7. Then vector_add_aligned runs the three loops, and the counts show where the instructions go.
# The three parts for the 5,404 returns of the lead, aligned and 8 bytes lateprint(split_work(5404, 0, 8), split_work(5404, 8, 8))for lanes, address in ((4, 0), (8, 0), (8, 8)): sim = LaneSim(lanes) vector_add_aligned(sim, [1.0] * 5404, [1.0] * 5404, address) print(lanes, "lanes, address", address, sim.total(), sim.counts)
(0, 5400, 4) (7, 5392, 5)
4 lanes, address 0 6755 {'loop': 1351, 'vload': 2702, 'vadd': 1351, 'vstore': 1351}
8 lanes, address 0 3395 {'loop': 679, 'vload': 1350, 'vadd': 675, 'vstore': 675, 'sload': 8, 'sadd': 4, 'sstore': 4}
8 lanes, address 8 3430 {'loop': 686, 'sload': 24, 'sadd': 12, 'sstore': 12, 'vload': 1348, 'vadd': 674, 'vstore': 674}Why bother with the head at all? Because of the cache. Memory moves in 64-byte lines, and a 32-byte load that starts 8 bytes past a multiple of 32 will, every other time, cover the end of one line and the start of the next. Such a split load is served as two accesses, so it costs more. line_crossings counts them, with and without the peel.
# Loads that straddle a 64-byte cache line over 5,400 elements: misaligned, then after peeling 3print(line_crossings(8, 5400, 4), "of", 5400 // 4)print(line_crossings(8 + 3 * 8, 5400, 4), "of", 5400 // 4)
675 of 1350 0 of 1350
- Way to deal with the tailCost and catch
- scalar tail loopFinish the last few elements one at a time.always correct, at most lanes - 1 slow passes
- pad the arrayAllocate a multiple of
lanesand fill the extra slots with zeros.no tail loop, but you own the padding - masked load and storeLoad and store only the live lanes of the last register.the next topic: masks
- overlap the last vectorRedo a full register that ends at the last element, overlapping the one before.only safe when recomputing a value is harmless
Typical mistakes
Losing the tail without an error. Mistake 1 in the second section never raised anything, and in a real sum the missing days simply make the result slightly wrong. A test that always uses a length divisible by the lane count will never catch it. This lab's tests draw random lengths for that reason: write your own tests with lengths one less and one more than a multiple of the width.
Assuming a slice is aligned. returns[1:] in NumPy is a view that starts one element, 8 bytes, into the buffer, so a kernel that assumed an aligned start now has a head of 3 on 4 lanes. If your kernel uses loads that require alignment, a slice makes it fail or crash; with unaligned loads it still works, but pays for the split loads shown above.
# A slice that starts one element (8 bytes) later needs a headfor start in (0, 1, 2, 3, 4): print("starts at element", start, "-> peel", peel_count(start * 8, 4))
starts at element 0 -> peel 0 starts at element 1 -> peel 3 starts at element 2 -> peel 2 starts at element 3 -> peel 1 starts at element 4 -> peel 0
If you allocate the array yourself, round its length up to a multiple of the width and fill the extra slots with a neutral value such as 0. Then the body covers everything and there is no tail loop to write or to get wrong.
What the tasks ask
- Task and functionWhat it must return
- is_aligned(address, width_bytes)
Truewhen the address is a multiple of the width.two error checks, in order - peel_count(address, lanes, itemsize=8)Single elements to handle before the address is aligned, from 0 to lanes - 1.address 8 on 4 lanes: 3
- split_work(n, address, lanes)
(head, body, tail)adding up ton, usingpeel_count.callspeel_count - vector_add_aligned(sim, a, b, address=0)The sum for any length: scalar head, vector body, scalar tail, with exact counts.uses
split_work
split_work give?Next. The scalar tail works, but it is a second loop to write and it runs slower than the body. The next topic shows a better tool for the same problem and for another one that has been waiting: the if inside a loop. A mask says which lanes of a register are live, so the last partial register can be loaded and stored with only its live lanes, and a branch such as "keep the return only if it is positive" becomes arithmetic with no jump.
Lab · what's graded
4 tasks · 100 pts- Test an address with
is_aligned25 pts - Count the elements to peel with
peel_count25 pts - Split the array with
split_work25 pts - Add any two arrays with
vector_add_aligned25 pts