我需要将Float32转换为Chisel FixedPoint,执行一些计算,然后将FixedPoint转换回Float32。

例如,我需要以下内容:

val a = 3.1F
val b = 2.2F
val res = a * b // REPL returns res: Float 6.82


现在,我这样做:

import chisel3.experimental.FixedPoint

val fp_tpe = FixedPoint(6.W, 2.BP)
val a_fix = a.Something (fp_tpe) // convert a to FixPoint
val b_fix = b.Something (fp_tpe) // convert b to FixPoint
val res_fix = a_fix * b_fix
val res0 = res_fix.Something (fp_tpe) // convert back to Float


结果,我希望增量在的范围内,例如

val eps = 1e-4
assert ( abs(res - res0) < eps, "The error is too big")


谁可以为上述伪代码的Chisel3 FixedPoint类提供一个工作示例?

最佳答案

看下面的代码:

import chisel3._
import chisel3.core.FixedPoint
import dsptools._


class FPMultiplier extends Module {
  val io = IO(new Bundle {
    val a = Input(FixedPoint(6.W, binaryPoint = 2.BP))
    val b = Input(FixedPoint(6.W, binaryPoint = 2.BP))
    val c = Output(FixedPoint(12.W, binaryPoint = 4.BP))
  })

  io.c := io.a * io.b
}

class FPMultiplierTester(c: FPMultiplier) extends DspTester(c) {
  //
  // This will PASS, there is sufficient precision to model the inputs
  //
  poke(c.io.a, 3.25)
  poke(c.io.b, 2.5)

  step(1)
  expect(c.io.c, 8.125)

  //
  // This will FAIL, there is not sufficient precision to model the inputs
  // But this is only caught on output, this is likely the right approach
  // because you can't really pass in wrong precision data in hardware.
  //
  poke(c.io.a, 3.1)
  poke(c.io.b, 2.2)

  step(1)
  expect(c.io.c, 6.82)
}


object FPMultiplierMain {
  def main(args: Array[String]): Unit = {
    iotesters.Driver.execute(Array("-fiv"), () => new FPMultiplier) { c =>
      new FPMultiplierTester(c)
    }
  }
}


我还建议您查看ParameterizedAdder中的dsptools,这使您有一种如何编写传递不同类型的硬件模块的感觉。通常,您从DspReals开始,确认模型,然后开始使用FixedPoint大小进行实验/计算,以返回所需精度的结果。

10-08 17:44