Search code examples
cneural-networkdeep-learningsignal-processingfixed-point

Porting Python/Matlab to C and to fixed-point DSP processor - should C be in fixed-point too?


I have a Python/Matlab code that does intensive Neural Network calculations. This Python/Matlab code will eventualy be ported to several target (fixed-point) DSP processor platforms (ARM, Tensillica, etc.). As an in-between step, the Python/Matlab code should be first ported to C on an x86 platform, thus becoming a sorf of a "reference" code.

The question is, should this C code be written in normal floating-point, or, does it bring any benefits for future DSP ports to write it immediately on x86 in fixed-point?


Solution

  • I would definitely recommend implementing you algorithm in fixed-point now. One tool that I have used to test my fixed-point implementations against Python floating-point reference implementations is ctypes to directly call your C functions from your Python code for direct comparison.

    For example, to use ctypes you must compile your fixed-point C functions into a shared object

    gcc -shared -std-gnu11 -g -o $(BIN_DIR)/libfm.so src/fxpt_atan2.c
    

    Then in your Python file

    import scipy as sp
    import ctypes as ct
    
    # Bind functions in shared object so they can be called in Python.
    fm = ct.CDLL('../build/x86/bin/libfm.so')
    
    # Create floating point reference.
    N = 1024
    n = sp.arange(N)
    x = sp.exp(2*sp.pi*1j*n/N)
    phi = sp.arctan2(sp.imag(x), sp.real(x))
    
    # Quantize input and process with fixed-point implementation.
    x_q, scale = quantize(x, normalize='pow2')
    phi_q = sp.zeros(len(x), dtype=sp.int16)
    for n in range(len(x)):
        # Call ctypes bound function from shared object.
        x_re_q = ct.c_int16(int(sp.real(x_q[n])))
        x_im_q = ct.c_int16(int(sp.imag(x_q[n])))
        phi_q[n] = fm.fxpt_atan2(x_im_q, x_re_q)
    
    # Compare floating point reference and fixed-point implementation.
    print(sp.allclose(phi, phi_q/scale*sp.pi, rtol=1e-3))