# -*- coding: utf-8 -*-
from setuptools import setup

packages = \
['hdtorch']

package_data = \
{'': ['*'], 'hdtorch': ['cuda/*']}

setup_kwargs = {
    'name': 'hdtorch',
    'version': '1.1.0',
    'description': 'HDTorch: Accelerating Hyperdimensional Computing with GP-GPUs for Design Space Exploration',
    'long_description': '# HDTorch\n\nHDTorch is PyTorch-based hyperdimensional (HD) computing library for HD learning.\nIt includes custom CUDA extensions for speeding up hypervector operations, namely, bit-(un)packing and bit-array summation in the horizontal/vertical dimensions.\n\nIn the paper [HDTorch: Accelerating Hyperdimensional Computing with GP-GPUs for Design Space Exploration (ICCAD 2022)](https://arxiv.org/abs/2206.04746), we demonstrate HDTorch’s utility by analyzing four HDC benchmark datasets in terms of accuracy, runtime, and memory consumption, utilizing both classical and online HD training methodologies.\n\n## Installation\n\nHDTorch is hosted on PyPi and can be installed via the following command:\n\n```\n   pip install hdtorch\n```\n\n## Basics of Hyperdimensional computing (HDC)\n\nHD computing is a machine learning strategy whose defining feature is its representation of data points as long (’hyper’) vectors, which enables learning by ’accumulation’ of said vectors belonging to the same class. HD computing relies on two conditions; first, any two randomly generated HD vectors are with high probability orthogonal, and second, a vector generated by vector accumulation will be more similar to its components than a vector not of its class.\n\nBinary and bipolar vectors are two common flavors of HD vector, consisting of values 0/1 and -1/1, respectively. In practice,  tertiary (-1,0,1) or integer/float vectors are sometimes used; however, this library focuses on binary and bipolar vectors\n\nThe typical HD workflow consists of several steps:\n\n1. Initialize basis vectors in memory that will be used to encode features. They represent the basic units we need, such as class vectors. If we have more complex data, such as EEG data, where we also have channels, we can have basis vectors for each of the channels too.\n\n2. Data (feature) values have to be discretized into several bins. Each of those values will have its own vector that was initialized in the previous step.\n\n3. Discretized features are encoded to HD vectors so that for each sample of features, we instead now have HD vector representing that sample.\n\n4. Learning is performed using all encoded data samples. Several approaches to learning are possible, but the most simple/classic approach is to accumulate all HD vectors representing samples of the same class. After accumulation and normalization to regain binary vectors, these vectors are called \'model\' vectors of classes. A more complex form of training is \'online\' training, which differs in that the class vectors are updated after every datapoint by multiplying its similarity to the target class by the vector before accumulating it into the class.\n\n5. Inference is performed by first encoding a test sample to an HD vector, then comparing it with learned \'model\' vectors. Comparison can be done via various metrics such as cosine, dot, or hamming similarity, but for binary vectors, hamming is the most memory and computation friendly. The label of the most similar \'model\' vector is given as a prediction.\n\n\n## Generating Hypervectors\n\n\nEncoding data such as a set of features to HD vectors can be done in several ways, but most of them, the first step is generating basis hypervectors that are further combined to generate the final HD vector representation of the original data.\n\nHere we provide several ways to initialize basis hypervectors, since the data that they represent can have different structures and relationships. For example, if we want to represent different categories with no inter-relationship, we can generate each HD vector randomly and independently. In contrast, values with inter-relationships may be mapped such that the distance between values is proportional to the distance between corresponding vectors.\n\nThus, several options to generate a set of basis vectors that our code supports now are:\n\n*  \'random\' - where every vector is  randomly and independently generated\n\n*  \'sandwich\' - where every two neighboring vectors have half of the vector the same, but the rest of the vector is random. Here, vectors share 50% similarity with neighboring vectors but not with the ones further.\n\n*  \'scale\' - or alternatively called \'level\' initialization, where the inter-distance between in values the vectors represent is mapped to the similarity between those vectors.\n\n*  \'scaleWithRadius\' - similar to \'scale\' initialization, but for vectors that are closer than the given \'radius\' distance. Thus, vectors closer than \'radius\' are similar proportionally to their distance, but beyond this \'radius\' they are orthogonal.\n\n\nExample of basis vectors generation:\n\n\n```\n    import hdtorch\n\n    # Generate 5 random hypervectors with dimension 10000 (not packed, on \'cuda\')\n    vecs = hdtorch.HDmodel.generateBasisHDVectors(\'random\',5,10000,0,\'cuda\')\n\n    # Generate 20 hypervectors with dimension 500 (not packed, on \'cuda\') in which two vectors are similar reverse-proportionally to their distance. Bits that are different between neighboring vectors are chosen in an increasing manner (instead of randomly) and the whole vector is eventually flipped. If the factor at the end was e.g. 2 only half of the total vector would be flipped.\n    vecs = hdtorch.HDmodel.generateBasisHDVectors(\'scaleNoRand1\',20,500,0,\'cuda\')\n\n    # Generate 100 hypervectors with dimension 10000 (not packed, on \'cuda\') who are similar in proportion to their distance up to the surrounding 10 vectors, and with all vectors further than that nearly orthogonal\n    vecs = hdtorch.HDmodel.generateBasisHDVectors(\'scaleWithRadius10\',1000,10000,0,\'cuda\')\n```\n\n## Custom CUDA functions\n\n\nIn order to significantly lower computation time and memory usage when operating with hypervectors, we implemented custom CUDA functions for packing, unpacking and manipulating them.\n\n\nBelow is shown how these functions are used:\n\n\n```\n    import hdtorch\n\n    # Generate random HD vectors of dimension 10000\n    vecs = hdtorch.HDmodel.generateBasisHDVectors(\'random\',5,10000,0,\'cuda\')\n\n    # Compress vectors to arrays with dimension [5,313], dtype = int32, (CUDA accelerated, 8x memory reduction). Dimension 313 is a result of ceil(10000/32)\n    packed_vecs = hdtorch.pack(vecs)\n\n    # Decompress vector to array with dimension [5,10000], dtype = int8 (CUDA accelerated)\n    unpacked_vecs = hdtorch.unpack(packed_vecs, 10000)\n```\n\nNext, as encoding and learning in HDC are based on bitwise summing vectors in horizontal and vertical dimensions, we implement these functions for packed vectors. This additionally reduces computation time for encoding and training.\n\nUsing those C-based functions is as follows:\n\n```\n    import hdtorch\n\n    # Generate random HD vectors of dimension 10000\n    vecs = hdtorch.HDmodel.generateBasisHDVectors(\'random\',5,10000,0,\'cuda\')\n\n    # Compress vectors to arrays with dimension [5,313], dtype = int32, (CUDA accelerated, 8x memory reduction).\n    packed_vecs = hdtorch.pack(vecs)\n\n    # Horizontal summation of packed vector (CUDA accelerated), the result is array with dimension [5]\n    h_count = hdtorch.hcount(packed_vecs)\n\n    # Vertical summation of packed vector (CUDA accelerated), the result is array with dimension [10000]\n    v_count = hdtorch.vcount(packed_vecs,10000)\n```\n\n\n\n\n## Data encoding\n\n\nIn order to learn from training data or infer test data labels, data has to be encoded to HD vectors. This means that instead of having data in the form of a 2D matrix [numSampl, numFeat] where each column is one feature, we represent it in the form of 2D matrix of corresponding HD vectors [numSampl, D]. For every sample, numFeat features are encoded to one D-dimensional hypervector.\n\nThere is many proposed encoding algorithms, but the most typical is what we call \'FeatXORVal\', where each features has an ID vector and n value vectors, where n is the range of values to which data samples are discretized. Data is encoded by binding for the feature ID vector to the value vector corresponding to the data\'s discretized value, typically via the XOR function. Finally, bound vectors are bundled for all features, generally via bitwise summing and normalizing by the number of summed vectors to regain binary vectors.\n\nThis method is demonstrated in the code below:\n\n```\n    import torch\n    import hdtorch\n\n    numFeat=30\n    D=10000\n    numSegmentationLevels=20\n\n    # initialize data (100 samples, with 30 features, having values between 0 and 256)\n    features=torch.randint(0,256,(100, numFeat)).to(device=\'cuda\')\n\n    # initialize basis vectors\n    featureIDs = hdtorch.HDmodel.generateBasisHDVectors(\'random\',numFeat,D,0,\'cuda\') #randomly generated feature ID vectors, 1 for each of 30 features, with with D=10000, non packed\n    featureVals = hdtorch.HDmodel.generateBasisHDVectors(\'scaleNoRand1\',numSegmentationLevels,D,0,\'cuda\') #generated feature value vectors, using \'scale\' method, 20 possible values, 1, with with D=10000, non packed\n\n    #normalize data\n    minFeat=torch.min(features, dim=0)[0]\n    maxFeat=torch.max(features, dim=0)[0]\n    featuresNorm = hdtorch.HDutil.normalizeAndDiscretizeData(features,minFeat, maxFeat, numSegmentationLevels )\n\n    #encode features using \'FeatXORVal\' approach\n    (encodedData, _) = hdtorch.HDencoding.EncodeDataToVectors (featuresNorm, featureIDs, featureVals, \'binary\', 0, \'FeatXORVal\', D)\n    # or using e.g. \'FeatPermute\' approach\n    (encodedData, _) = hdtorch.HDencoding.EncodeDataToVectors (featuresNorm, featureIDs, featureVals, \'binary\', 0, \'FeatPermute\', D)\n```\n\n## HD computing learning and inference\n\n\nFinally, to use HD vectors to perform learning and inference, we show the whole process on an training and inference example using MNIST data:\n\n```\n    import torch\n    import hdtorch\n    from torchvision import datasets\n    import torchvision.transforms as transforms\n\n    # Setting various parameters\n    class HDParams():\n        HDFlavor = \'binary\'  # \'binary\', \'bipol\' #binary 0,1, bipolar -1,1\n        D = 10000  # dimension of hypervectors\n        numFeat = 784\n        numClasses = 10\n        device = \'cuda\'  # device to use (cpu, cuda)\n        packed = True\n        numSegmentationLevels = 20 # defines number of discretization levels to which data is discretized\n        similarityType = \'hamming\'  # \'hamming\',\'cosine\' #similarity measure used for comparing HD vectors\n        levelVecType = \'random\'  # \'random\',\'sandwich\',\'scaleNoRand1\',\'scaleNoRand2\',\'scaleRand1\', ,\'scaleRand2\'... \'scaleWithRadius3\', #defines how HD vectors are initialized\n        IDVecType = \'random\'\n        encodingStrat =  \'FeatXORVal\' # \'FeatXORVal\' \'FeatAppend\' \'FeatPermute\'   #defines how HD vectors encoded\n    hdParams = HDParams()\n    batchSize = 1000 #learn in batches\n\n    # Loading MNIST dataset\n    print("Loading MNIST dataset")\n    t = transforms.Compose([transforms.ToTensor(), transforms.ConvertImageDtype(torch.uint8)])\n    kwargs = {\'num_workers\': 1, \'pin_memory\': True} if HDParams.device == \'cuda\' else {}\n    dataTrain = datasets.MNIST(root = \'./data\', train = True, transform = t, download = True)\n    dataTest  = datasets.MNIST(root = \'./data\', train = False, transform = t, download = True)\n    trainLoader = torch.utils.data.DataLoader(dataset=dataTrain, batch_size=batchSize, shuffle=True, **kwargs)\n    testLoader  = torch.utils.data.DataLoader(dataset=dataTest, batch_size=batchSize, shuffle=False, **kwargs)\n\n    # Calculate min and max valus on train set - will used for also normalizing test set\n    minFeat = trainLoader.dataset.data.view(-1,784).min(0)[0].to(HDParams.device)\n    maxFeat = trainLoader.dataset.data.view(-1,784).max(0)[0].to(HDParams.device)\n\n    # Initialize HD classifier\n    HDModel = hdtorch.HD_classifier(HDParams)\n\n    # Training HD model in batches\n    print("Training Model")\n    for x,(data,labels) in enumerate(trainLoader):\n        print(f\'Training batch {x}\')\n        data = data.to(HDParams.device).view(-1,784)\n        data = hdtorch.HDutil.normalizeAndDiscretizeData(data,minFeat, maxFeat, HDParams.numSegmentationLevels )\n        HDModel.trainModelVecOnData(data,labels.to(HDParams.device))\n\n    # Testing performance\n    print("Testing Model")\n    for x,(data,labels) in enumerate(testLoader):\n        data = data.to(HDParams.device).view(-1,784)\n        data = hdtorch.HDutil.normalizeAndDiscretizeData(data, minFeat, maxFeat, HDParams.numSegmentationLevels)\n        (testPredictions,testDistances) = HDModel.givePrediction(data)\n        acc_test = (testPredictions == labels.to(HDParams.device)).sum().item()/len(labels)\n        print(f\'Batch {x}: Acc: {acc_test}\')\n```\n\n## Documentation\n\nMore documentation on HDTorch\'s individual features can be found on its [Read the Docs page](https://hdtorch.readthedocs.io/en/latest/).\n\n### License\n\nThis library is [MIT licensed](https://github.com/hyperdimensional-computing/torchhd/blob/main/LICENSE).\n\n## Citations\n\nIf you like this work and use it in your own research, it would be appreciated to cite our following work:\n```\n@INPROCEEDINGS{iccad2022,\n  author={Simon, William Andrew and Pale, Una and Teijeiro, Tomas and Atienza, David},\n  booktitle={2022 IEEE/ACM International Conference On Computer Aided Design (ICCAD)},\n  title={HDTorch: Accelerating Hyperdimensional Computing with GP-GPUs for Design Space Exploration},\n  year={2022}}\n```',
    'author': 'wasimon',
    'author_email': 'william.simon@epfl.ch',
    'maintainer': 'None',
    'maintainer_email': 'None',
    'url': 'https://c4science.ch/source/hdtorch/',
    'packages': packages,
    'package_data': package_data,
    'python_requires': '>=3.6,<4.0',
}


setup(**setup_kwargs)
