1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
|
# mypy: allow-untyped-defs
import argparse
import sys
# Unroll loops when block_size is a multiple of vector length.
def unroll(num_unrolls, IndexType, InType, OutType, use_weights):
def compute(regid, InType, use_weights):
code = []
if InType == "float":
code.append(
f" vsum{regid} =\n"
" svmad_f32_x("
f"svAll, vwgt, svld1_f32(svAll, &ip[{regid} * vLen]),"
f" vsum{regid});"
)
elif InType == "at::Half":
code.append(
f" vsum{regid} = svmad_f32_x(\n"
" svAll,\n"
" vwgt,\n"
" svcvt_f32_f16_x(\n"
" svAll,\n"
" svreinterpret_f16_u32(svld1uh_u32(\n"
" svAll, reinterpret_cast<const uint16_t*>("
f"&ip[{regid} * vLen])))),\n" # noqa
f" vsum{regid});"
)
elif InType == "at::BFloat16":
code.append(
f" vsum{regid} = svmad_f32_x(\n"
" svAll,\n"
" vwgt,\n"
" svreinterpret_f32_u32(svlsl_n_u32_x(\n"
" svAll,\n"
" svld1uh_u32(\n"
" svAll, reinterpret_cast<const uint16_t*>("
f"&ip[{regid} * vLen])),\n"
" 16)),\n" # noqa
f" vsum{regid});"
)
elif InType == "uint8_t":
code.append(
f" vsum{regid} = svmad_f32_x(\n"
" svAll,\n"
" vwgt,\n"
" svcvt_f32_u32_x(svAll,"
f" svld1ub_u32(svAll, &ip[{regid} * vLen])),\n" # noqa
f" svadd_f32_x(svAll, vsum{regid}, vbio));"
)
else:
raise ValueError(f"Unknown datatype \"{InType}\"")
return code
code = []
code.append(f" // unrolling {num_unrolls} times")
code.append(" for (int64_t i = 0; i < output_size; ++i) {")
code.append(" " + OutType + "* const op = &out[i * block_size];")
code.append(
" if (pos != offsets[i] - offsets[0]) {\n"
+ " return false;\n"
+ " }"
)
# Initialise vector sum registers
for i in range(num_unrolls):
code.append(f" svfloat32_t vsum{i} = svdup_n_f32(0);")
# inner loop
code.append("""\
int64_t start_offset = offsets[i];
int64_t end_offset = offsets[i + 1];""")
code.append(
" for ("
+ "int64_t"
+ " j = start_offset; j < end_offset; ++j) {" # noqa
)
code.append(" const auto idx = indices[pos];")
code.append(
" if (idx < 0 || idx >= data_size) {\n"
+ " return false;\n"
+ " }"
)
if InType == "uint8_t":
code.append(" " + OutType + " wgt = 1.f;")
code.append(" " + OutType + " bio{};")
code.append(" if (weights) {")
code.append(
" wgt = weights[IS_WEIGHT_POSITIONAL ? (j - start_offset) : pos];" # noqa
)
code.append(" }")
code.append(" if (scale_bias) {")
code.append(" bio = wgt * scale_bias[2 * idx + 1];")
code.append(" wgt = wgt * scale_bias[2 * idx];")
code.append(" }")
code.append(" svfloat32_t vbio = svdup_n_f32(bio);")
else:
code.append(" " + OutType + " wgt = 1.f;")
code.append(" if (weights) {")
code.append(
" wgt = weights[IS_WEIGHT_POSITIONAL ? (j - start_offset) : pos];" # noqa
)
code.append(" }")
code.append(" const svfloat32_t vwgt = svdup_n_f32(wgt);")
code.append(f" const {InType}* const ip = &input[idx * block_size];")
code.append(" // weight * input + out")
for i in range(num_unrolls):
code.extend(compute(i, InType, use_weights))
code.append(" ++pos;")
code.append(" }")
code.append(" // Normalisation")
code.append(" const int64_t length = end_offset - start_offset;")
code.append(" if (normalize_by_lengths && length != 0) {")
code.append(" const float len_inv = 1.0f / length;")
code.append(" const svfloat32_t vlen_inv = svdup_n_f32(len_inv);")
for i in range(num_unrolls):
code.append(f" svst1_f32(svAll, &op[{i} * vLen],"
+ f" svmul_f32_x(svAll, vsum{i}, vlen_inv));")
code.append(" } else {")
# inv of length
for i in range(num_unrolls):
code.append(f" svst1_f32(svAll, &op[{i} * vLen], vsum{i});")
code.append(" }")
code.append(" }")
return code
# Handle the case where block_size is not a multiple of vector length.
def generic(IndexType, InType, OutType, use_weights):
def compute(InType, use_weights):
code = []
if InType == "float":
code.append(
" svst1_f32(\n"
" pg,\n"
" &op[k],\n"
" svmad_f32_x(\n"
" pg, vwgt, svld1_f32(pg, &ip[k]),"
" svld1_f32(pg, &op[k])));"
)
elif InType == "at::Half":
code.append(
" svst1_f32(\n"
" pg,\n"
" &op[k],\n"
" svmad_f32_x(\n"
" pg,\n"
" vwgt,\n"
" svcvt_f32_f16_x(\n"
" pg,\n"
" svreinterpret_f16_u32(svld1uh_u32(\n"
" pg,"
" reinterpret_cast<const uint16_t*>(&ip[k])))),\n"
" svld1_f32(pg, &op[k])));"
)
elif InType == "at::BFloat16":
code.append(
" svst1_f32(\n"
" pg,\n"
" &op[k],\n"
" svmad_f32_x(\n"
" pg,\n"
" vwgt,\n"
" svreinterpret_f32_u32(svlsl_n_u32_x(\n"
" pg,\n"
" svld1uh_u32(\n"
" pg,"
" reinterpret_cast<const uint16_t*>(&ip[k])),\n"
" 16)),\n"
" svld1_f32(pg, &op[k])));"
)
elif InType == "uint8_t":
code.append(
" svst1_f32(\n"
" pg,\n"
" &op[k],\n"
" svmad_f32_x(\n"
" pg,\n"
" vwgt,\n"
" svcvt_f32_u32_x(pg,"
" svld1ub_u32(pg, &ip[k])),\n" # noqa
" svadd_f32_x(pg,"
" svld1_f32(pg, &op[k]), vbio)));"
)
else:
raise ValueError(f"Unknown datatype \"{InType}\"")
return code
code = []
code.append(
" for (int64_t i = 0; i < output_size; ++i) {"
)
code.append(" " + OutType + "* const op = &out[i * block_size];")
# initialize to 0
code.append(" memset(op, 0, sizeof(float) * block_size);")
# inner loop
code.append(
" if (pos != offsets[i] - offsets[0]) {\n"
+ " return false;\n"
+ " }"
)
code.append(
" int64_t start_offset = offsets[i];\n"
+ " int64_t end_offset = offsets[i + 1];"
)
code.append(
" for ("
+ "int64_t"
+ " j = start_offset; j < end_offset; ++j) {" # noqa
)
code.append(" const auto idx = indices[pos];")
code.append(
" if (idx < 0 || idx >= data_size) {\n"
+ " return false;\n"
+ " }"
)
if InType == "uint8_t":
code.append(" // unimplemented")
code.append(" " + OutType + " wgt = 1.f;")
code.append(" " + OutType + " bio{};")
code.append(" if (weights) {")
code.append(
" wgt = weights[IS_WEIGHT_POSITIONAL ? (j - start_offset) : pos];" # noqa
)
code.append(" }")
code.append(" if (scale_bias) {")
code.append(" bio = wgt * scale_bias[2 * idx + 1];")
code.append(" wgt = wgt * scale_bias[2 * idx];")
code.append(" }")
code.append(" svfloat32_t vbio = svdup_n_f32(bio);")
else:
code.append(" " + OutType + " wgt = 1.f;")
code.append(" if (weights) {")
code.append(
" wgt = weights[IS_WEIGHT_POSITIONAL ? (j - start_offset) : pos];" # noqa
)
code.append(" }")
code.append(" const svfloat32_t vwgt = svdup_n_f32(wgt);")
code.append(f" const {InType}* ip = &input[idx * block_size];")
# compute and store main loop
code.append(" svbool_t pg;")
code.append(" for (int64_t k = 0;")
code.append(" svptest_first(svAll, pg = svwhilelt_b32_s64("
+ "k, block_size));")
code.append(" k += vLen) {")
code.extend(compute(InType, use_weights))
code.append(" }\n")
code.append(" ++pos;")
code.append(" }")
code.append(" const int64_t length = end_offset - start_offset;\n")
code.append(" if (normalize_by_lengths && length != 0) {")
code.append(" const float len_inv = 1.0f / length;")
code.append(" svfloat32_t vlen_inv = svdup_n_f32(len_inv);")
code.append(" svbool_t pg;")
code.append(" for (int64_t j = 0;\n"
" svptest_first(svAll, pg = svwhilelt_b32_s64("
"j, block_size));")
code.append(" j += vLen) {")
code.append(
" svst1_f32(\n"
" pg, &op[j], svmul_f32_x(pg, svld1_f32(pg, &op[j]), vlen_inv));"
)
code.append(" }")
code.append(" }")
code.append(" }")
return code
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--filename", help="file name")
opts = parser.parse_args()
if opts.filename:
filename = opts.filename
else:
filename = "embedding_lookup_idx_sve.cc"
options = [
["int32_t", "int32_t", "float", "float", "float", "float"],
["int64_t", "int64_t", "float", "float", "float", "float"],
["int32_t", "int32_t", "half", "at::Half", "float", "float"],
["int64_t", "int64_t", "half", "at::Half", "float", "float"],
["int32_t", "int32_t", "bfloat16", "at::BFloat16", "float", "float"],
["int64_t", "int64_t", "bfloat16", "at::BFloat16", "float", "float"],
["int32_t", "int32_t", "uint8_t", "uint8_t", "float", "float"],
["int64_t", "int64_t", "uint8_t", "uint8_t", "float", "float"],
]
code = []
# includes
code.append("//// --------------------------")
code.append("//// ATTENTION:")
code.append("//// THIS CODE IS AUTOGENERATED")
code.append(f"//// BY {' '.join(sys.argv)}")
code.append("//// DO NOT MODIFY!!!")
code.append("//// --------------------------\n")
code.append("#include <arm_sve.h>")
code.append("#include <c10/util/BFloat16.h>")
code.append("#include <c10/util/Half.h>")
code.append("#include <cstdint>")
code.append("#include <cstring>")
code.append("namespace caffe2 {\n")
for o in options:
[IndexTypeName, IndexType, InTypeName, InType, OutTypeName, OutType] = o
code.append("template <bool IS_WEIGHT_POSITIONAL>")
fn_base = f"EmbeddingLookupIdx_{IndexTypeName}_{InTypeName}_{OutTypeName}"
suffix = "__sve"
fn = "static bool " + fn_base + suffix
code.append(fn + "(")
args = []
args.append(" const int64_t block_size,")
args.append(" const int64_t output_size,")
args.append(" const int64_t index_size,")
args.append(" const int64_t data_size,")
args.append(" const " + InType + "* input,")
args.append(" const " + IndexType + "* indices,")
args.append(" const " + IndexType + "* offsets,")
args.append(" const float* weights,")
args.append(" const float* scale_bias,")
args.append(" bool normalize_by_lengths,")
args.append(" " + OutType + "* out) {")
code += args
code.append(" const svbool_t svAll = svptrue_b32();")
code.append(" const auto vLen = static_cast<int64_t>(svcntw());")
code.append(" int64_t pos = 0;")
code.append(" if (block_size == 32 * vLen) {")
code += unroll(32, IndexType, InType, OutType, True)
code.append(" } else if (block_size == 16 * vLen) {")
code += unroll(16, IndexType, InType, OutType, True)
code.append(" } else if (block_size == 8 * vLen) {")
code += unroll(8, IndexType, InType, OutType, True)
code.append(" } else if (block_size == 4 * vLen) {")
code += unroll(4, IndexType, InType, OutType, True)
code.append(" } else if (block_size == 2 * vLen) {")
code += unroll(2, IndexType, InType, OutType, True)
code.append(" } else {")
code.append(" // generic code:")
code += generic(IndexType, InType, OutType, True)
code.append(" }")
code.append(" return pos == index_size;")
code.append("}")
for is_weight_positional in ["false", "true"]:
code.append("bool " + fn_base + "_" + is_weight_positional + suffix + "(")
code += args
# Resolve the Lint warnings: Limit of 80 characters in one line.
extra_space = "\n "
ret_string = " return " + fn_base + suffix \
+ "<" + is_weight_positional + ">("
if len(ret_string) <= 80:
code.append(ret_string)
else:
code.append(" return " + fn_base + suffix + "<" + extra_space + is_weight_positional + ">(")
code.append(" block_size,")
code.append(" output_size,")
code.append(" index_size,")
code.append(" data_size,")
code.append(" input,")
code.append(" indices,")
code.append(" offsets,")
code.append(" weights,")
code.append(" scale_bias,")
code.append(" normalize_by_lengths,")
code.append(" out);")
code.append("}")
code.append("")
code.append("} // namespace caffe2")
with open(filename, "w") as fout:
fout.write("\n".join(code) + "\n")
print("Created " + filename)
if __name__ == "__main__":
main()
|