Vector
Operations in PicturesFor each i
, set c[i] = a[i] + b[i]
Vector
Operations in Code int step = SPECIES.length();
int bound = SPECIES.loopBound(a.length);
int i = 0;
for (; i < bound; i += step) {
var va = FloatVector.fromArray(SPECIES, a, i);
var vb = FloatVector.fromArray(SPECIES, b, i);
var vc = va.add(vb);
vc.intoArray(c, i);
}
Question. What if we don’t want to apply an operation to all entries in a Vector
?
E.g., conditional assignment:
for (int i = 0; i < a.length; i++) {
if (b[i] > 0) {
c[i] = a[i] + b[i];
} else {
c[i] = a[i];
}
}
To apply an operation (say, add
) only to some lanes:
true
Set c[i] = a[i] + b[i]
if b[i] > 0
and c[i] = a[i]
otherwise
VectorMask<Float>
datatype: think Vector
of Boolean
smasked arithmetic operations:
public final FloatVector add(Vector<Float> v,
VectorMask<Float> m)
“Adds this vector to a second input vector, selecting lanes under the control of a mask. This is a masked lane-wise binary operation which applies the primitive addition operation (+
) to each pair of corresponding lane values. For any lane unset in the mask, the primitive operation is suppressed and this vector retains the original value stored in that lane. This method is also equivalent to the expression lanewise(ADD, v, m)
.”
A VectorMask<Float>
that is true
when b[i] > 0
:
var va = FloatVector.fromArray(SPECIES, a, i);
var vb = FloatVector.fromArray(SPECIES, b, i);
var bMask = vb.compare(VectorOperators.GT, 0);
var vc = va.add(vb, bMask);
Definition. Given an int a
, the Hamming weight of a
is the number of 1
s in the binary representation of a
.
Question. How to compute Hamming weight of int a
?
&
Bitwise &
operator, a & b
:
How to determine if bit i
is 0
or 1
?
Idea. For bits i = 1...32
, check if bit i
is 1
In code:
int val;
int idx = 1;
int weight = 0;
for (int j = 0; j < INT_LENGTH; j++) {
if ((val & idx) != 0) {
weight++;
}
idx = idx << 1;
}
// weight is the Hamming weight of val
Want to compute Hamming weight of an array of int
s…
for (int j = 0; j < INT_LENGTH; j++) {
if ((val & idx) != 0) {
weight++;
}
idx = idx << 1;
}
How could we vectorize this method?
va
from array of valuesvb
initialized to all 0
int idx
has 1
in exactly one bit positionidx
:
1
if i
th bit of va
lane is 1
1
to corresponding lanesvar va = IntVector.fromArray(SPECIES, a, i);
var vb = IntVector.broadcast(SPECIES, 0);
int idx = 1;
for (int j = 0; j < INT_LENGTH; j++) {
var bitMask = va.and(idx).eq(0).not();
vb = vb.add(1, bitMask);
idx = idx << 1;
}
vb.intoArray(b, i);
HammingWeight.java
DemoTo give “accurate” measure of efficiency:
Draw this picture as quickly as possible!