Example #1
0
def DefineLinebuffer(cirb: CoreIRBackend,
                     inType: ArrayKind,
                     outType: ArrayKind,
                     imgType: ArrayKind,
                     has_valid=False):
    """
    Implements a linebuffer for image pipelines. inType is an array of how many pixels
    are inputted per clock. outType is an array of how many pixels are emitted per clock.
    imgType is the size of the total image.

    inType and outType are nested arrays of elementType if doing linebuffer over a 2d (or higher dimension)
    image. Their nesting should match number of dimensions.

    inType, outType, and imgType must be arrays of elementType

    Args:
        cirb: The CoreIR backend currently be used
        inType: The type of the input every clock
        outType: The type of the output every clock following warmup
        imgType: The type of the complete image
        elementType: The elements of the image, typically this is a pixel
        has_valid: Whether this module should have an output port denoting if output data
        is valid this clock

    Returns:
        A module with the following ports:
        I : In(inType)
        out : Out(outType)
        wen : In(Bit) -- this is a clock enable port. TODO: wrap this module and call it CE

        AND IF VALID SET
        valid : Out(Bit)
        valid_chain : Out(Bit) (this is an internal property that is being
        exposed on linebuffer's external interface. always send it to a term)
    """
    # Reason for weird False/True settings in get_type
    # get_type does some funky things, False means not input, and since
    # looking from inside module, output port is an input as it receives input
    # But, linebuffer wants these ports from perspective of outside,
    # so need inverse, inputs are BitIns and outputs are Bits
    cirInType = cirb.get_type(inType, False)
    cirOutType = cirb.get_type(outType, True)
    cirImgType = cirb.get_type(imgType, False)
    strForValid = "_Valid" if has_valid else ""
    name = "linebuffer_in{}_out{}_img{}{}".format(cleanName(str(inType)),
                                                  cleanName(str(outType)),
                                                  cleanName(str(imgType)),
                                                  strForValid)
    # this is the linebuffer with the outputs as a flat array, unsplit
    defToReturn = DefineCircuitFromGeneratorWrapper(
        cirb, "commonlib", "linebuffer", "unioned_" + name,
        ["mantle", "coreir", "global"], {
            "input_type": cirInType,
            "output_type": cirOutType,
            "image_type": cirImgType,
            "has_valid": has_valid
        })

    return defToReturn
Example #2
0
def test_up_sequential():
    width = 5
    numOut = 2
    testVal = 3
    c = coreir.Context()
    scope = Scope()
    inType = Array(width, In(BitIn))
    outType = Out(inType)
    args = ['I', inType, 'O', outType, 'READY',
            Out(Bit)] + ClockInterface(False, False)

    testcircuit = DefineCircuit('TestUpSequential', *args)

    coreir_backend = CoreIRBackend(c)
    upSequential = UpsampleSequential(coreir_backend, numOut, inType)
    wire(upSequential.I, testcircuit.I)
    wire(testcircuit.O, upSequential.O)
    wire(testcircuit.READY, upSequential.READY)

    EndCircuit()

    sim = CoreIRSimulator(testcircuit,
                          testcircuit.CLK,
                          context=coreir_backend.context)

    sim.set_value(testcircuit.I, int2seq(testVal, width), scope)
    sim.evaluate()

    for i in range(numOut):
        assert seq2int(sim.get_value(testcircuit.O, scope)) == testVal
        sim.advance_cycle()
        sim.evaluate()
        assert sim.get_value(testcircuit.READY, scope) == (i == numOut - 1)
Example #3
0
def test_1dlb_flicker_ce_with_2_stride():
    scope = Scope()
    c = coreir.Context()
    cirb = CoreIRBackend(c)

    testcircuit = DefineOneDimensionalLineBuffer(cirb, Array[8, In(Bit)], 1, 2,
                                                 8, 2, 0, True)

    sim = CoreIRSimulator(testcircuit,
                          testcircuit.CLK,
                          context=c,
                          namespaces=[
                              "aetherlinglib", "commonlib", "mantle", "coreir",
                              "global"
                          ])

    for i in range(50):
        if i % 2 == 0:
            sim.set_value(testcircuit.I[0], int2seq(1, 8), scope)
            sim.set_value(testcircuit.CE, 1, scope)
        else:
            sim.set_value(testcircuit.I[0], int2seq(2, 8), scope)
            sim.set_value(testcircuit.CE, 0, scope)
        sim.evaluate()
        sim.advance_cycle()
        sim.evaluate()
        print([
            seq2int(sim.get_value(testcircuit.O[0][r], scope))
            for r in range(2)
        ])
        print(sim.get_value(testcircuit.valid, scope))
        # for some reason, lb going to 0 when flickering valid on and off for ce
        for r in range(2):
            assert (sim.get_value(testcircuit.valid, scope) == 0
                    or seq2int(sim.get_value(testcircuit.O[0][r], scope)) != 0)
Example #4
0
def test_two_coreir_muxes():
    width = 2
    c = coreir.Context()
    cirb = CoreIRBackend(c)
    scope = Scope()
    inType = Array(width, In(BitIn))
    outType = Array(width, Out(Bit))
    args = ['I', inType, 'S', In(Bit), 'O', outType] + ClockInterface(
        False, False)

    testcircuit = DefineCircuit('test_partition', *args)
    coreir_mux = DefineCoreirMux(None)()
    coreir_mux(testcircuit.I[0], testcircuit.I[1], testcircuit.S)
    wire(coreir_mux.out, testcircuit.O[0])
    cmux = CommonlibMuxN(cirb, 2, 1)
    wire(cmux.I.data[0][0], testcircuit.I[0])
    wire(cmux.I.data[1][0], testcircuit.I[1])
    wire(cmux.I.sel[0], testcircuit.S)
    wire(cmux.out[0], testcircuit.O[1])

    EndCircuit()

    sim = CoreIRSimulator(
        testcircuit,
        testcircuit.CLK,
        context=c,
        namespaces=["commonlib", "mantle", "coreir", "global"])
Example #5
0
def test_ram_flicker_we():
    scope = Scope()
    c = coreir.Context()
    cirb = CoreIRBackend(c)

    testcircuit = DefineRAM(8, 1)

    sim = CoreIRSimulator(testcircuit,
                          testcircuit.CLK,
                          context=c,
                          namespaces=[
                              "aetherlinglib", "commonlib", "mantle", "coreir",
                              "global"
                          ])

    sim.set_value(testcircuit.WADDR[0], 0, scope)
    sim.set_value(testcircuit.RADDR[0], 0, scope)
    sim.set_value(testcircuit.WDATA[0], 1, scope)
    for i in range(20):
        sim.set_value(testcircuit.WE, 0, scope)
        sim.evaluate()
        sim.advance_cycle()
    sim.set_value(testcircuit.WE, 1, scope)
    sim.evaluate()
    sim.advance_cycle()
    sim.set_value(testcircuit.WE, 0, scope)
    sim.evaluate()
    sim.advance_cycle()
    print(sim.get_value(testcircuit.RDATA, scope))
Example #6
0
def test_partition():
    width = 8
    parallelism = 2
    testValInt = 210
    testValBits = int2seq(testValInt)
    c = coreir.Context()
    cirb = CoreIRBackend(c)
    scope = Scope()
    inType = Array(width, In(BitIn))
    outType = Array(parallelism, Out(Bit))
    args = ['I', inType, 'O', outType] + ClockInterface(False, False)

    testcircuit = DefineCircuit('test_partition', *args)

    part = Partition(cirb, inType, parallelism)
    wire(part.I, testcircuit.I)
    wire(testcircuit.O, part.O)

    EndCircuit()

    sim = CoreIRSimulator(testcircuit,
                          testcircuit.CLK,
                          context=cirb.context,
                          namespaces=[
                              "aetherlinglib", "commonlib", "mantle", "coreir",
                              "global"
                          ])

    sim.set_value(testcircuit.I, int2seq(testValInt, width), scope)
    sim.evaluate()
    for i in range(int(width / parallelism)):
        assert seq2int(sim.get_value(testcircuit.O, scope)) == \
               seq2int(testValBits[i*parallelism:(i+1)*parallelism])
        sim.advance_cycle()
        sim.evaluate()
Example #7
0
def test_db_flicker_ce():
    scope = Scope()
    c = coreir.Context()
    cirb = CoreIRBackend(c)

    testcircuit = DefineDelayedBuffer(cirb, Array[8, Bit], 4, 1, 16, 1)

    sim = CoreIRSimulator(testcircuit,
                          testcircuit.CLK,
                          context=c,
                          namespaces=[
                              "aetherlinglib", "commonlib", "mantle", "coreir",
                              "global"
                          ])

    for i in range(100000):
        if i % 2 == 0 and i > 20:
            sim.set_value(testcircuit.I[0], int2seq(1, 8), scope)
            sim.set_value(testcircuit.CE, 1, scope)
        else:
            sim.set_value(testcircuit.I[0], int2seq(2, 8), scope)
            sim.set_value(testcircuit.CE, 0, scope)
        if i % 2 == 0 and i > 20:  #(not i % 16 == 0 or i == 0):
            sim.set_value(testcircuit.WE, 1, scope)
        else:
            sim.set_value(testcircuit.WE, 0, scope)
        sim.evaluate()
        print(seq2int(sim.get_value(testcircuit.O[0], scope)))
        print(sim.get_value(testcircuit.valid, scope))

        # for some reason, lb going to 0 when flickering valid on and off for ce
        assert (sim.get_value(testcircuit.valid, scope) == 0
                or seq2int(sim.get_value(testcircuit.O[0], scope)) != 0)
        sim.advance_cycle()
Example #8
0
def test_downsample_parallel():
    width = 5
    numIn = 2
    testVal = 3
    c = coreir.Context()
    cirb = CoreIRBackend(c)
    scope = Scope()
    outType = Array(width, Out(BitIn))
    inType = Array(numIn, In(outType))
    args = ['I', inType, 'O', outType] + ClockInterface(False, False)

    testcircuit = DefineCircuit('Test_Downsample_Parallel', *args)

    downsampleParallel = DownsampleParallel(cirb, numIn, inType.T)
    wire(downsampleParallel.I, testcircuit.I)
    wire(testcircuit.O, downsampleParallel.O)

    EndCircuit()

    sim = CoreIRSimulator(testcircuit,
                          testcircuit.CLK,
                          context=cirb.context,
                          namespaces=[
                              "aetherlinglib", "commonlib", "mantle", "coreir",
                              "global"
                          ])

    for i in range(numIn):
        sim.set_value(testcircuit.I[i], int2seq(testVal, width), scope)
    sim.evaluate()
    assert seq2int(sim.get_value(testcircuit.O, scope)) == testVal
Example #9
0
def test_deserializer():
    width = 11
    numIn = 13
    c = coreir.Context()
    cirb = CoreIRBackend(c)
    scope = Scope()
    inType = In(Array(width, Bit))
    outType = Out(Array(numIn, Array(width, BitIn)))
    args = ['I', inType, 'O', outType, 'valid',
            Out(Bit)] + ClockInterface(False, False)

    testcircuit = DefineCircuit('Test_Deserializer', *args)

    deserializer = Deserializer(cirb, inType, numIn)
    wire(deserializer.I, testcircuit.I)
    wire(testcircuit.O, deserializer.out)
    wire(testcircuit.valid, deserializer.valid)

    EndCircuit()

    sim = CoreIRSimulator(testcircuit,
                          testcircuit.CLK,
                          context=cirb.context,
                          namespaces=[
                              "aetherlinglib", "commonlib", "mantle", "coreir",
                              "global"
                          ])

    for i in range(numIn):
        sim.set_value(testcircuit.I, int2seq(i, width), scope)
        assert sim.get_value(testcircuit.valid, scope) == (i == numIn - 1)
        sim.evaluate()
        sim.advance_cycle()
        sim.evaluate()
    assert sim.get_value(testcircuit.valid, scope) == False
Example #10
0
def test_simulator_tuple():
    width = 8
    testValInt = 80
    c = coreir.Context()
    cirb = CoreIRBackend(c)
    scope = Scope()
    inDims = [2, width]
    tupleEl = Array[inDims[1], Bit]
    nestedTuples = Array[inDims[0], Tuple(sel=tupleEl, data=tupleEl)]
    tupleValues = {'sel':int2seq(testValInt, width), 'data':int2seq(testValInt+20, width)}
    inType = In(nestedTuples)
    outType = Out(Array[2*inDims[0], tupleEl])
    args = ['I', inType, 'O', outType] + ClockInterface(False, False)

    testcircuit = DefineCircuit('test_simulator_tuple', *args)

    wire(testcircuit.I[0].data, testcircuit.O[0])
    wire(testcircuit.I[0].sel, testcircuit.O[1])
    wire(testcircuit.I[1].data, testcircuit.O[2])
    wire(testcircuit.I[1].sel, testcircuit.O[3])

    EndCircuit()

    sim = CoreIRSimulator(testcircuit, testcircuit.CLK, context=cirb.context,
                          namespaces=["aetherlinglib", "commonlib", "mantle", "coreir", "global"])

    sim.set_value(testcircuit.I, [tupleValues, tupleValues], scope)
    getArrayInTuple = sim.get_value(testcircuit.I[0].data, scope)
    getTuples = sim.get_value(testcircuit.I, scope)
    assert getArrayInTuple == tupleValues['data']
    assert getTuples[0] == tupleValues
    assert getTuples[1] == tupleValues
Example #11
0
def test_reduce_parallel():
    width = 11
    numIn = 13
    c = coreir.Context()
    cirb = CoreIRBackend(c)
    scope = Scope()
    inType = In(Array(numIn, Array(width, BitIn)))
    outType = Out(Array(width, Bit))
    args = ['I', inType, 'O', outType] + ClockInterface(False, False)

    testcircuit = DefineCircuit('Test_Reduce_Parallel', *args)

    reducePar = ReduceParallel(cirb, numIn,
                               renameCircuitForReduce(DefineAdd(width)))
    coreirConst = DefineCoreirConst(width, 0)()
    wire(reducePar.I.data, testcircuit.I)
    wire(reducePar.I.identity, coreirConst.out)
    wire(testcircuit.O, reducePar.out)

    EndCircuit()

    sim = CoreIRSimulator(testcircuit,
                          testcircuit.CLK,
                          context=cirb.context,
                          namespaces=[
                              "aetherlinglib", "commonlib", "mantle", "coreir",
                              "global"
                          ])

    for i in range(numIn):
        sim.set_value(testcircuit.I[i], int2seq(i, width), scope)
    sim.evaluate()
    assert seq2int(sim.get_value(testcircuit.O, scope)) == sum(range(numIn))
Example #12
0
def DefineDehydrate(cirb: CoreIRBackend, T: Kind):
    """
    Convert a nested type to a flat array of bits
    Aetherling Type: {1, T} -> {1, Bit[width(T)]}
    This returns a circuit definition.

    Args:
        cirb: The CoreIR backend currently be used
        T: The type to dehydrate

    Returns:
        A module with the following ports:
        I : In(T)
        out : Out(Array(width(T), Bit))

        The module also has the following data:
        size: width(T)
    """
    cirType = cirb.get_type(T, True)
    name = "dehydrate_t{}".format(cleanName(str(T)))
    defToReturn = DefineCircuitFromGeneratorWrapper(
        cirb, "aetherlinglib", "dehydrate", name,
        ["commonlib", "mantle", "coreir", "global"], {"hydratedType": cirType})
    defToReturn.size = cirType.size
    return defToReturn
Example #13
0
def test_nested_clocks():
    c = coreir.Context()
    cirb = CoreIRBackend(c)
    args = ['clocks', In(Array[2, Clock])]

    inner_test_circuit = DefineCircuit('inner_test_nested_clocks', *args)
    EndCircuit()

    test_circuit = DefineCircuit('test_nested_clocks', *args)
    inner_test_circuit()
    EndCircuit()
    GetCoreIRModule(cirb, test_circuit)
Example #14
0
def run_test_updown_npxPerClock(pxPerClock):
    upsampleAmount = 7
    c = coreir.Context()
    cirb = CoreIRBackend(c)
    scope = Scope()
    args = ClockInterface(False, False) + RAMInterface(imgSrc, True, True,
                                                       pxPerClock)

    testcircuit = DefineCircuit(
        'Test_UpsampleDownsample_{}PxPerClock'.format(pxPerClock), *args)

    imgData = loadImage(imgSrc, pxPerClock)
    pixelType = Array(imgData.bitsPerPixel, Bit)
    bitsToPixelHydrate = MapParallel(cirb, pxPerClock,
                                     Hydrate(cirb, pixelType))
    upParallel = MapParallel(cirb, pxPerClock,
                             UpsampleParallel(upsampleAmount, pixelType))
    downParallel = MapParallel(
        cirb, pxPerClock, DownsampleParallel(cirb, upsampleAmount, pixelType))
    pixelToBitsDehydrate = MapParallel(cirb, pxPerClock,
                                       Dehydrate(cirb, pixelType))

    # Note: input image RAM will send data to hydrate,
    # which converts it to form upsample and downsample can use
    # note that these do wiriring to connect the RAMs to edge of test circuit and
    # adjacent node inside circuit
    InputImageRAM(cirb, testcircuit, bitsToPixelHydrate.I, imgSrc, pxPerClock)
    OutputImageRAM(cirb, testcircuit, pixelToBitsDehydrate.out,
                   testcircuit.input_ren, imgSrc, pxPerClock)
    wire(upParallel.I, bitsToPixelHydrate.out)
    wire(upParallel.O, downParallel.I)
    wire(downParallel.O, pixelToBitsDehydrate.I)

    EndCircuit()

    #GetCoreIRModule(cirb, testcircuit).save_to_file("updown_out{}.json".format(pxPerClock))

    sim = CoreIRSimulator(testcircuit,
                          testcircuit.CLK,
                          context=cirb.context,
                          namespaces=[
                              "aetherlinglib", "commonlib", "mantle", "coreir",
                              "global"
                          ])

    LoadImageRAMForSimulation(sim, testcircuit, scope, imgSrc, pxPerClock)
    # run the simulation for all the rows
    for i in range(imgData.numRows):
        sim.evaluate()
        sim.advance_cycle()
        sim.evaluate()
    DumpImageRAMForSimulation(sim, testcircuit, scope, imgSrc, pxPerClock,
                              validIfEqual)
Example #15
0
def DeclareCoreIRGenerator(lib : str, name : str, typegen = None, backend = None):
    if backend is None:
        backend = CoreIRBackend()
    if typegen is not None:
        # This is for generators which we don't have access to
        raise NotImplementedError()
    else:
        # Assume the generator is available, create a wrapped circuit
        def Define(**kwargs):
            kwargs_str = "_".join(f"{key}_{value}" for key, value in kwargs.items())
            unique_name = f"{lib}_{name}_{kwargs_str}"
            return DefineCircuitFromGeneratorWrapper(backend, lib, name, unique_name, genargs=kwargs, runGenerators=False)
        return Define
Example #16
0
def Flatten(cirb: CoreIRBackend, inputType: Kind, singleElementOutputType: Kind) -> Circuit:
    """
    Flatten a nested list to a single list. The nested list can be flattened across multiple dimensions
    with a single flatten node. The output list can be nested, but if so must be flatter than the input list.
    Aetherling Type: T[k]...[s] -> T[k*...*s] (... means potentially many lists/lengths)

    :param cirb: The CoreIR backend currently be used
    :param inputType: The nested lists input type
    :param singleElementOutputType: The element type T that will be emitted. It can be a list itself, but it must be
     an element (at some level of nesting) in inputType.
    :return: A list with elements of type singleElementOutputType that is of the appropriate length
    for the flatteneing.
    I : In(inputType)
    O : Out(Array(singleElementOutputType, k*...*s))
    """
    cirInputType = cirb.get_type(inputType, True)
    cirSingleEleementOutputType = cirb.get_type(singleElementOutputType, True)
    name = "dehydrate_tin{}_tout".format(cleanName(str(cirInputType)), cleanName(str(singleElementOutputType)))
    moduleToReturn = CircuitInstanceFromGeneratorWrapper(cirb, "aetherlinglib", "flatten", name,
                                                         ["commonlib", "mantle", "coreir", "global"],
                                                         {"inputType": cirInputType,
                                                          "singleElementOutputType": cirSingleEleementOutputType})
    return moduleToReturn
Example #17
0
def simulator_nested(simple):
    width = 8
    testValInt = 80
    testValBits = int2seq(testValInt)
    c = coreir.Context()
    cirb = CoreIRBackend(c)
    scope = Scope()
    inDims = [4, 3, width]
    toNest = Array[inDims[1], Array[inDims[2], Bit]]
    inType = In(Array[inDims[0], toNest])
    if simple:
        outType = Out(Array[inDims[0], toNest])
    else:
        outType = Out(Array[2, Array[2, toNest]])
    args = ['I', inType, 'O', outType] + ClockInterface(False, False)

    testcircuit = DefineCircuit(
        'test_simulator_nested_simple{}'.format(str(simple)), *args)

    if simple:
        wire(testcircuit.I, testcircuit.O)
    else:
        wire(testcircuit.I[:2], testcircuit.O[0])
        wire(testcircuit.I[2:4], testcircuit.O[1])

    EndCircuit()

    sim = CoreIRSimulator(testcircuit,
                          testcircuit.CLK,
                          context=cirb.context,
                          namespaces=[
                              "aetherlinglib", "commonlib", "mantle", "coreir",
                              "global"
                          ])

    for i in range(inDims[0]):
        for j in range(inDims[1]):
            get = sim.get_value(testcircuit.I[i][j], scope)
            assert (len(get) == width)
            sim.set_value(testcircuit.I[i][j],
                          int2seq((((i * inDims[1]) + j) * inDims[2]), width),
                          scope)

    sim.evaluate()
    sim.get_value(testcircuit.I, scope)
    sim.get_value(testcircuit.O, scope)
Example #18
0
def test_linebuffer_2pxPerClock_4pxWindow():
    c = coreir.Context()
    cirb = CoreIRBackend(c)
    scope = Scope()
    width = 8
    inType = Array(2, Array(width, BitIn))
    outType = Array(4, Array(width, Out(Bit)))
    imgType = Array(30, Array(width, BitIn))
    args = ['I', inType, 'O', outType, 'valid',
            Out(Bit)] + ClockInterface(False, False)

    testcircuit = DefineCircuit('lb1_3_Test', *args)

    lb = Linebuffer(cirb, inType, outType, imgType, True)
    wire(lb.I, testcircuit.I)
    wire(testcircuit.O, lb.out)

    wire(1, lb.wen)
    wire(lb.valid, testcircuit.valid)
    validChainTerm = Term(cirb, 1)
    wire(lb.valid_chain, validChainTerm.I[0])

    EndCircuit()

    sim = CoreIRSimulator(testcircuit,
                          testcircuit.CLK,
                          context=cirb.context,
                          namespaces=[
                              "aetherlinglib", "commonlib", "mantle", "coreir",
                              "global"
                          ])

    for i in range(3):
        sim.set_value(testcircuit.I[0], int2seq(2 * i, width), scope)
        sim.set_value(testcircuit.I[1], int2seq(2 * i + 1, width), scope)
        sim.evaluate()
        assert sim.get_value(testcircuit.valid, scope) == (i >= 1)
        if i >= 1:
            assert seq2int(sim.get_value(testcircuit.O[0],
                                         scope)) == (i - 1) * 2
            assert seq2int(sim.get_value(testcircuit.O[1],
                                         scope)) == (i - 1) * 2 + 1
            assert seq2int(sim.get_value(testcircuit.O[2], scope)) == i * 2
            assert seq2int(sim.get_value(testcircuit.O[3], scope)) == i * 2 + 1
        sim.advance_cycle()
        sim.evaluate()
Example #19
0
def GetCoreIRModule(cirb: CoreIRBackend, circuit: DefineCircuitKind):
    """
    Get the CoreIR module corresponding to the Magma circuit or circuit instance

    :param cirb: The CoreIR backend currently be used.
    :param circuit: The magma circuit to get the coreIR backend for
    :return: A CoreIR module
    """
    if (hasattr(circuit, "wrappedModule")):
        return circuit.wrappedModule
    else:
        # if this is an instance, compile the class, as that is the circuit
        if circuit.is_instance:
            circuitNotInstance = circuit.__class__
        else:
            circuitNotInstance = circuit
        return cirb.compile(circuitNotInstance)[circuitNotInstance.name]
Example #20
0
def test_linebuffer_1pxPerClock_3pxWindow():
    c = coreir.Context()
    cirb = CoreIRBackend(c)
    scope = Scope()
    inType = Array(1, Array(3, BitIn))
    outType = Array(3, Array(3, Out(Bit)))
    imgType = Array(30, Array(3, BitIn))
    args = ['I', inType, 'O', outType] + ClockInterface(False, False)

    testcircuit = DefineCircuit('lb1_3_Test', *args)

    lb = Linebuffer(cirb, inType, outType, imgType, False)
    wire(lb.I, testcircuit.I)
    wire(testcircuit.O, lb.out)

    wire(1, lb.wen)

    EndCircuit()
Example #21
0
def test_downsample_sequential():
    width = 5
    numOut = 2
    testVal = 3
    c = coreir.Context()
    scope = Scope()
    outType = Array(width, Out(BitIn))
    inType = In(outType)
    args = ['I', inType, 'O', outType, 'VALID',
            Out(Bit)] + ClockInterface(False, False)

    testcircuit = DefineCircuit('Test_Downsample_Sequential', *args)

    cirb = CoreIRBackend(c)
    downsampleSequential = DownsampleSequential(numOut, inType)
    wire(downsampleSequential.I, testcircuit.I)
    wire(testcircuit.O, downsampleSequential.O)
    wire(testcircuit.VALID, downsampleSequential.VALID)
    EndCircuit()

    #testModule = GetCoreIRModule(cirb, testcircuit)
    #cirb.context.run_passes(["rungenerators", "verifyconnectivity-noclkrst"], ["aetherlinglib", "commonlib", "mantle", "coreir", "global"])
    #testModule.save_to_file("downsampleSequential.json")

    sim = CoreIRSimulator(testcircuit,
                          testcircuit.CLK,
                          context=cirb.context,
                          namespaces=[
                              "aetherlinglib", "commonlib", "mantle", "coreir",
                              "global"
                          ])

    sim.set_value(testcircuit.I, int2seq(testVal, width), scope)
    sim.evaluate()

    for i in range(numOut):
        assert seq2int(sim.get_value(testcircuit.O, scope)) == testVal
        assert sim.get_value(testcircuit.VALID, scope) == (i == 0)
        sim.advance_cycle()
        sim.evaluate()
Example #22
0
def test_linebuffer_2pxPerClock_3pxWindow():
    c = coreir.Context()
    cirb = CoreIRBackend(c)
    scope = Scope()
    elementType = Array(3, Bit)
    pxPerClock = 2
    stencilWidth = 3
    inType = In(Array(pxPerClock, elementType))
    outType = Out(Array(pxPerClock, Array(stencilWidth, elementType)))
    imgType = Array(30, elementType)
    args = ['I', inType, 'O', outType] + ClockInterface(False, False)

    testcircuit = DefineCircuit('lb1_3_Test', *args)

    lb = Linebuffer1DPartitioned(cirb, pxPerClock, stencilWidth, elementType,
                                 imgType)
    wire(lb.I, testcircuit.I)
    wire(testcircuit.O, lb.O)

    wire(1, lb.CE)

    EndCircuit()
Example #23
0
def test_reduce_sequential():
    width = 11
    numIn = 13
    c = coreir.Context()
    cirb = CoreIRBackend(c)
    scope = Scope()
    inType = In(Array(width, BitIn))
    outType = Out(Array(width, Bit))
    args = ['I', inType, 'O', outType, 'valid',
            Out(Bit)] + ClockInterface(False, False)

    testcircuit = DefineCircuit('Test_Reduce_Parallel', *args)

    reduceSeq = ReduceSequential(cirb, numIn,
                                 renameCircuitForReduce(DefineAdd(width)))
    wire(reduceSeq.I, testcircuit.I)
    wire(testcircuit.O, reduceSeq.out)
    wire(testcircuit.valid, reduceSeq.valid)

    EndCircuit()

    sim = CoreIRSimulator(testcircuit,
                          testcircuit.CLK,
                          context=cirb.context,
                          namespaces=[
                              "aetherlinglib", "commonlib", "mantle", "coreir",
                              "global"
                          ])

    for i in range(numIn):
        sim.set_value(testcircuit.I, int2seq(i, width), scope)
        sim.evaluate()
        # exit last time of loop without going to next iteration, time to check results then
        if i < numIn - 1:
            assert sim.get_value(testcircuit.valid, scope) == False
            sim.advance_cycle()
            sim.evaluate()
    assert seq2int(sim.get_value(testcircuit.O, scope)) == sum(range(numIn))
    assert sim.get_value(testcircuit.valid, scope) == True
Example #24
0
def GetCoreIRModule(cirb: CoreIRBackend, circuit: DefineCircuitKind):
    """
    Get the CoreIR module corresponding to the Magma circuit or circuit instance

    :param cirb: The CoreIR backend currently be used.
    :param circuit: The magma circuit to get the coreIR backend for
    :return: A CoreIR module
    """
    if (hasattr(circuit, "wrappedModule")):
        return circuit.wrappedModule
    else:
        # if this is an instance, compile the class, as that is the circuit
        if hasattr(circuit, 'is_instance') and circuit.is_instance:
            circuitNotInstance = circuit.__class__
        else:
            circuitNotInstance = circuit
        moduleOrGenerator = cirb.compile(circuitNotInstance)[circuitNotInstance.name]
        # compile can giv eme back the coreIR module or the coreIR generator. if this is
        # the CoreIR generator, call it with the Magma arguments converted to CoreIR ones.
        if isinstance(moduleOrGenerator, Generator):
            return moduleOrGenerator(**circuitNotInstance.coreir_genargs)
        else:
            return moduleOrGenerator
Example #25
0
def test_ram1x8():
    c = coreir.Context()
    cirb = CoreIRBackend(c)

    testcircuit = DefineRAM(1, 8)
    CoreIRSimulator(testcircuit, testcircuit.CLK, context=cirb.context)
Example #26
0
def test_any_type_ram_flicker_we():
    scope = Scope()
    c = coreir.Context()
    cirb = CoreIRBackend(c)

    testcircuit = DefineRAMAnyType(cirb, Array[4, Array[8, Bit]],
                                   4)  #DefineRAM(8, 1)

    sim = CoreIRSimulator(testcircuit,
                          testcircuit.CLK,
                          context=c,
                          namespaces=[
                              "aetherlinglib", "commonlib", "mantle", "coreir",
                              "global"
                          ])

    sim.set_value(testcircuit.WADDR[0], 0, scope)
    sim.set_value(testcircuit.RADDR[0], 0, scope)
    sim.set_value(testcircuit.WDATA[0], int2seq(0, 8), scope)
    sim.set_value(testcircuit.WDATA[1], int2seq(0, 8), scope)
    sim.set_value(testcircuit.WDATA[2], int2seq(0, 8), scope)
    sim.set_value(testcircuit.WDATA[3], int2seq(0, 8), scope)
    sim.set_value(testcircuit.WE, 0, scope)
    for i in range(20):
        sim.evaluate()
        if i == 0:
            sim.set_value(testcircuit.WDATA[0], int2seq(1, 8), scope)
        if i == 2:
            sim.set_value(testcircuit.WDATA[1], int2seq(1, 8), scope)
        if i == 16:
            sim.set_value(testcircuit.WDATA[2], int2seq(1, 8), scope)
        if i == 18:
            sim.set_value(testcircuit.WDATA[3], int2seq(1, 8), scope)
        sim.evaluate()
        sim.advance_cycle()
        sim.evaluate()
        print("WDATA: " + str([
            seq2int(sim.get_value(testcircuit.WDATA, scope)[r])
            for r in range(4)
        ]))
        print("RDATA: " + str([
            seq2int(sim.get_value(testcircuit.RDATA, scope)[r])
            for r in range(4)
        ]))
    sim.set_value(testcircuit.WE, 1, scope)
    sim.evaluate()
    sim.advance_cycle()
    sim.evaluate()
    sim.set_value(testcircuit.WDATA[0], int2seq(0, 8), scope)
    sim.set_value(testcircuit.WDATA[1], int2seq(0, 8), scope)
    sim.set_value(testcircuit.WDATA[2], int2seq(0, 8), scope)
    sim.set_value(testcircuit.WDATA[3], int2seq(0, 8), scope)
    print("RDATA: " + str([
        seq2int(sim.get_value(testcircuit.RDATA, scope)[r]) for r in range(4)
    ]))
    sim.set_value(testcircuit.WE, 0, scope)
    sim.evaluate()
    sim.advance_cycle()
    sim.evaluate()
    print("RDATA: " + str([
        seq2int(sim.get_value(testcircuit.RDATA, scope)[r]) for r in range(4)
    ]))
Example #27
0
def test_2dlb_flicker_ce_with_2x2_stride():
    scope = Scope()
    c = coreir.Context()
    cirb = CoreIRBackend(c)

    testcircuit = DefineTwoDimensionalLineBuffer(cirb, Array[8, In(Bit)], 1, 1,
                                                 2, 2, 8, 8, 2, 2, 0, 0, True)

    #magma.compile("2dlbflicker_1001pm_2_11_19_unflattened", testcircuit, output="coreir-verilog",
    #              passes=["rungenerators", "wireclocks-coreir", "verifyconnectivity --noclkrst", "verifyconnectivity --noclkrst", "deletedeadinstances"],
    #              namespaces=["aetherlinglib", "commonlib", "mantle", "coreir", "global"], context = c)
    #magma.compile("2dlbflicker_912pm_2_11_19_flattened", testcircuit, output="coreir-verilog",
    #              passes=["rungenerators", "wireclocks-coreir", "verifyconnectivity --noclkrst", "flattentypes", "flatten", "verifyconnectivity --noclkrst", "deletedeadinstances"],
    #              namespaces=["aetherlinglib", "commonlib", "mantle", "coreir", "global"], context = c)
    #tcm = GetCoreIRModule(cirb, testcircuit)
    #cirb.context.run_passes(, )
    #tcm.save_to_file("2dlbflicker.json")

    sim = CoreIRSimulator(testcircuit,
                          testcircuit.CLK,
                          context=c,
                          namespaces=[
                              "aetherlinglib", "commonlib", "mantle", "coreir",
                              "global"
                          ])

    for i in range(100000):
        if i % 2 == 0:
            sim.set_value(testcircuit.I[0][0], int2seq(1, 8), scope)
            sim.set_value(testcircuit.CE, 1, scope)
        else:
            sim.set_value(testcircuit.I[0][0], int2seq(2, 8), scope)
            sim.set_value(testcircuit.CE, 0, scope)
        sim.evaluate()
        sim.advance_cycle()
        sim.evaluate()
        print("i" + str(i))
        print("undelayed out: " + str([
            seq2int(sim.get_value(testcircuit.undelayedO[0][r][c], scope))
            for r in range(2) for c in range(2)
        ]))
        print("out: " + str([
            seq2int(sim.get_value(testcircuit.O[0][r][c], scope))
            for r in range(2) for c in range(2)
        ]))
        print("valid: " + str(sim.get_value(testcircuit.valid, scope)))
        print("db CE: " + str(sim.get_value(testcircuit.dbCE, scope)))
        print("db WE: " + str(sim.get_value(testcircuit.dbWE, scope)))
        print("db RDATA: " + str([
            seq2int(sim.get_value(testcircuit.RDATA, scope)[0][r][c])
            for r in range(2) for c in range(2)
        ]))
        print("db WDATA: " + str([
            seq2int(sim.get_value(testcircuit.WDATA, scope)[0][r][c])
            for r in range(2) for c in range(2)
        ]))
        print("db RADDR: " +
              str(seq2int(sim.get_value(testcircuit.RADDR, scope)[0])))
        print("db WADDR: " +
              str(seq2int(sim.get_value(testcircuit.WADDR, scope)[0])))
        print("db RAM WE: " + str(sim.get_value(testcircuit.RAMWE, scope)))
        print("")
        print("")
Example #28
0
def test_clock_adjusted_2dlb_flicker_ce_with_2x2_stride():
    c = coreir.Context()
    cirb = CoreIRBackend(c)

    testcircuit = DefineTwoDimensionalLineBuffer(cirb, Array[8, In(Bit)], 1, 1,
                                                 2, 2, 8, 8, 2, 2, 0, 0, True)

    magma.compile("vBuild/" + testcircuit.name,
                  testcircuit,
                  output="coreir-verilog",
                  passes=[
                      "rungenerators", "wireclocks-coreir",
                      "verifyconnectivity --noclkrst", "flattentypes",
                      "flatten", "verifyconnectivity --noclkrst",
                      "deletedeadinstances"
                  ],
                  namespaces=[
                      "aetherlinglib", "commonlib", "mantle", "coreir",
                      "global"
                  ],
                  context=c)
    tester = fault.Tester(testcircuit, testcircuit.CLK)

    for i in range(30):
        if i % 2 == 0:
            tester.poke(testcircuit.I[0][0], 1)
            tester.poke(testcircuit.CE, 1)
        else:
            tester.poke(testcircuit.I[0][0], 2)
            tester.poke(testcircuit.CE, 0)

        tester.eval()
        tester.step(2)
        tester.eval()

        print_start_clock(tester)
        print_nd_bit_array_port(tester, testcircuit.valid, name="valid")
        print_nd_int_array_port(tester, testcircuit.O, name="O")
        print_end_clock(tester)
        #tester.print(testcircuit.O, f"{i}: %x \\n")
        # tester.print(testcircuit.I, f"{start_string} {i} Input:  %x\\n")
        # for some reason, lb going to 0 when flickering valid on and off for ce
        for r in range(2):
            for c in range(2):
                if r == 0 and c == 0:
                    inner_start_string = "[["
                    inner_end_string = ", "
                elif c == 0:
                    inner_start_string = "["
                    inner_end_string = ", "
                elif r == 1 and c == 1:
                    inner_start_string = ""
                    inner_end_string = "]], "
                elif c == 1:
                    inner_start_string = ""
                    inner_end_string = "], "
                #tester.print(testcircuit.O[0][r][c], f"{inner_start_string}%x{inner_end_string}")
                #tester.expect(testcircuit.O[0][r][c], 1)
                # tester.circuit.O[0][r][c].expect(1)
    tester.compile_and_run(target="verilator",
                           skip_compile=True,
                           directory="vBuild/")
    with open(get_fault_log(__file__, testcircuit.name)) as file:
        results = eval("[" + file.read() + "]")
        print(len(results))
        print(results[0])
Example #29
0
def test_2dlb_flicker_ce_with_2x2_stride_ross_clock_instructions():
    scope = Scope()
    c = coreir.Context()
    cirb = CoreIRBackend(c)

    testcircuit = DefineTwoDimensionalLineBuffer(cirb, Array[8, In(Bit)], 1, 1,
                                                 2, 2, 8, 8, 2, 2, 0, 0, True)

    sim = CoreIRSimulator(testcircuit,
                          testcircuit.CLK,
                          context=c,
                          namespaces=[
                              "aetherlinglib", "commonlib", "mantle", "coreir",
                              "global"
                          ])

    sim.set_value(testcircuit.CE, 1, scope)
    sim.set_value(testcircuit.I[0][0], int2seq(1, 8), scope)
    sim.evaluate()
    sim.set_value(testcircuit.CLK, 1, scope)
    sim.evaluate()
    for i in range(100000):
        sim.set_value(testcircuit.CLK, 0, scope)
        sim.evaluate()
        print("CLK: " + str(sim.get_value(testcircuit.CLK, scope)))
        print("i" + str(i))
        print("undelayed out: " + str([
            seq2int(sim.get_value(testcircuit.undelayedO[0][r][c], scope))
            for r in range(2) for c in range(2)
        ]))
        print("out: " + str([
            seq2int(sim.get_value(testcircuit.O[0][r][c], scope))
            for r in range(2) for c in range(2)
        ]))
        print("valid: " + str(sim.get_value(testcircuit.valid, scope)))
        print("db CE: " + str(sim.get_value(testcircuit.dbCE, scope)))
        print("db WE: " + str(sim.get_value(testcircuit.dbWE, scope)))
        print("db RDATA: " + str([
            seq2int(sim.get_value(testcircuit.RDATA, scope)[0][r][c])
            for r in range(2) for c in range(2)
        ]))
        print("db WDATA: " + str([
            seq2int(sim.get_value(testcircuit.WDATA, scope)[0][r][c])
            for r in range(2) for c in range(2)
        ]))
        print("db RADDR: " +
              str(seq2int(sim.get_value(testcircuit.RADDR, scope)[0])))
        print("db WADDR: " +
              str(seq2int(sim.get_value(testcircuit.WADDR, scope)[0])))
        print("db RAM WE: " + str(sim.get_value(testcircuit.RAMWE, scope)))
        print("")
        print("")

        sim.set_value(testcircuit.CLK, 1, scope)
        sim.evaluate()
        print("CLK: " + str(sim.get_value(testcircuit.CLK, scope)))

        if i % 2 == 1:
            sim.set_value(testcircuit.I[0][0], int2seq(1, 8), scope)
            sim.set_value(testcircuit.CE, 1, scope)
        else:
            sim.set_value(testcircuit.I[0][0], int2seq(2, 8), scope)
            sim.set_value(testcircuit.CE, 0, scope)

        sim.evaluate()
Example #30
0
from mantle import CounterModM, Decode, SIPO
from magma.frontend.coreir_ import GetCoreIRModule
from mantle.coreir.arith import *
from mantle.primitives import DeclareAdd

# downscale factor (a x b)
a = 11
b = 9
samples = 16

# image dimensions (height and width)
im_w = 320
im_h = 240

c = coreir.Context()
cirb = CoreIRBackend(c)

# 8-bit values but extend to 16-bit to avoid carryover in addition
width = 16
TIN = m.Array(width, m.BitIn)
TOUT = m.Array(width, m.Out(m.Bit))

# Line Buffer interface
inType = m.Array(1, m.Array(1, TIN))  # one pixel in per clock
outType = m.Array(b, m.Array(a, TOUT))  # downscale window
imgType = m.Array(im_h, m.Array(im_w, TIN))  # image dimensions

# Reduce interface
inType2 = m.In(m.Array(a * b, TIN))
outType2 = TOUT