#adlrocha - A story about how machine learning and blockchain fell in love
A longly announced love story.
Spanish version below! (Translation: Cada vez me siento más tentado de pasar la versión inglesa a través de Deepl —una vez más, no uso Google— y ver qué sale de ahí. Puede que lo haga un día de estos).
How many times have you heard that “blockchain is going to change the way we do machine learning and artificial intelligence”? Thousand of them, right? Well, Microsoft has made a step forward in this artificial intelligence and blockchain love story.
One of the things I hated the most when I was trying to learn machine learning and artificial intelligence by myself is the need of tons and tons of data in order to make my models work. Even more, the companies that are thriving in this field right now are those capable of acquiring huge amounts of data to do their artificial intelligence right. But what is left for small companies and common mortals lacking the the data, the dedicated hardware and the resources to do AI right? This is what Microsoft Research is trying to tackle with their new development.
As you may already know, the current artificial intelligence paradigm is the following: machine learning systems are highly centralized and owned by a small set of companies. Their predictions are often sold on a per-query basis (when offered to the public at all), and the datasets required to train them are generally proprietary and expensive —or impossible— to recreate due to the lack of access to data. Additionally, publicly offered models run the risk of easily becoming outdated if new data is not regularly provided to retrain/update them (and we were already lacking the access to sources of data to make this happen by ourselves, remember?).
What is Microsoft envisioning to shift this paradigm? A Decentralized and Collaborative AI on Blockchain. This idea is not new, and it has already been proposed by several startups, but it is the first time that one of the big ones proposes it. Through this new framework, “participants would be collaboratively and continually training and maintaining models, as well as building datasets, on public blockchains, where models are generally free to use for evaluating predictions”.
What does blockchain have to do with this?
Blockchain offers two things to the system: trust (forget about having to trust a centralized system or a single corporation for your training and predictions), and a way of implementing in a secure and reliable manner an incentive-based system to encourage participants to contribute data and improve models.
In the current AI paradigm, you are generally making use of specialized central cloud services that you don’t control nor know what is being run in it, even if it is your own model and you are using open source software. The use of blockchain technology and smart contracts offer a level of trust and accountability to the code being run in the infrastructure. In Microsoft’s proposal, public models are put into smart contracts to ensure that the specifications agreed upon for a model are held. Thus, users can update models on-chain for a small transaction fee, or off-chain in their local device with no transaction costs.
This could open the door to a way of tackling with one of the main concerns around artificial intelligence right now: data privacy. Imagine that when using your preferred personal assistant (Siri, Cortana, Alexa, Jarvis, etc.) you could choose a public model stored on-chain that you know how is using your data to retrain the model, and where you are benefitting from the use of the system by other users of the system; or that you (as a “privacy-paranoid” individual) don’t want to use the public model, and you are able to download a base public model to your device, and exclusively update it locally with your own personal data (it wouldn’t be as accurate as when a lot of users were contributing to its training, but is private enough for you). Sounds interesting, right?
How does the system work?
First of all, the model that wants to be used is uploaded to the blockchain platform (implemented in a smart contract). In their current implementation, Microsoft has set up a simple Perceptron model for use cases such as sentiment analysis (it is not easy to implement complex machine learning models over smart contract yet. It is an interesting field of research though). It is better if when uploading models they have a basic level of training in order to achieve a decent accuracy from scratch. With the model published in the system, users are able to add data to it in order to retrain the model, or make predictions using their own data (see following figure).
Collaboration through incentives.
Microsoft proposes a set of incentive mechanisms to encourage people to contribute new data to the system in order to maintain the models performance. Initially, they propose three incentive models:
Gamified: This incentive mechanism is based on the willingness of the community to contribute to a common good. In exchange for their contributions, users could be rewarded with points, badges or currency/utility tokens (to make queries to the model, for instance?).
Prediction market-based: This is a more interesting approach. In this incentive mechanism, contributors get rewarded if their data improves the performance of the model. This builds on works such as “A collaborative Mechanism for Crowdsourcing Prediction Problems” and “A Market Framework for Eliciting Private Data”. The use of cryptoeconomic models such as these are in the core of blockchain systems, and they are a great tool to encourage good behaviours in users. If you want a visual peak of how this incentive mechanism works, check the next figure.
Ongoing self-assesment: In this mechanism participants effectively validate and pay each other for good data contributions. In such scenarios, an existing model already trained with some data is deployed. A contributor wishing to update the model submits data with features x, label y, and a deposit. After some predetermined time has passed, if the current model still agrees with the classification, then the person gets their deposit back. We now assume the data has been validated as “good,” and that contributor earns a point. If a contributor adds “bad” data—that is, data that cannot be validated as “good”—then the contributor’s deposit is forfeited and split among contributors who’ve earned points for “good” contributions. Such a reward system would help deter the malicious contribution of “bad” data.
Aren't smart contracts just for simple code?
I know, this may have been one of your main concerns when reading the article. To answer this question let me share with you Microsoft Research team’s answer in their Github repo:
“There are many options. We can restrict the framework to simple models: Perceptron, Naive Bayes, Nearest Centroid, etc. We can also combine off-chain computation with on-chain computation in a few ways such as:
encoding off-chain to a higher dimensional representation and just have the final layers of the model fine-tuned on-chain,
using secure multiparty computation, or
using external APIs, or as they are called the blockchain space, oracles, to train and run the model
We can also use algorithms that do not require all models parameters to be updated (e.g. Perceptron). We hope to inspire more research in efficient ways to update more complex models.
Some of those proposals are not in the true spirit of this system which is to share models completely publicly but for some applications they may be suitable. At least the data would be shared so others can still use it to train their own models.”
This excerpt has interesting ideas that I have taken the liberty of highlighting for your personal enjoyment.
Conclusions
With this framework Microsoft aims to offer a system to easily share models and collectively contribute with diverse data to the models to increase their accuracy. It is a good first (and maybe obvious) step forward the AI + blockchain relationship. This work opens interesting questions for further research:
Can we envision more advanced smart contract programming languages and execution environments to enable the execution of complex and hardware intensive decentralized artifical intelligence models?
The hardware required to train artificial intelligence is expensive and scarce (only a set of cloud computing providers “rent” them). Can we develop a way of indistinctly using any of the publicly-offered cloud-based global resources for training my model (similar to what projects like iExec or Ankr are trying to do)?
And if we end up using dedicated hardware and sharing data with a lot of external entities, how can we ensure that privacy is ensured? Here is where advanced cryptographic primitives (I may talk about this in a few weeks) such as secure multiparty computation (mentioned above), homomorphic encryption and zero-knowledge proofs; or the training models using federated learning, come to play.
We will have to keep an eye on the developments around this new couple. Will they have a happy ending? Can you think of any other use case where blockchain and AI are a perfect match? Let me know!
References:
Some updates from last week:
We were talking about European regulations in the tech sector, remember?
Una historia sobre como se enamoraron la inteligencia artificial y el blockchain
¿Cuántas veces hemos oído aquello de “la tecnología blockchain va a cambiar la forma en la que concebimos la inteligencia artificial y el machine learning”? Miles de veces, ¿verdad? Bueno, pues Microsoft acaba de publicar un artículo con una propuesta que avanza ligeramente en la historia de amor entre el blockchain y la inteligencia artificial.
Una de las cosas que más odiaba cuando decidí empezar a aprender por mi cuenta un poco sobre inteligencia artificial y machine learning era la necesidad de tener esas grandes cantidades de datos necesarias para hacer funcionar el modelo de manera razonable. Aún más, es un hecho que las compañías a las que mejor les va en el campo de la inteligencia artificial actualmente son aquellas que tienen acceso a grandes cantidades de datos para hacer sus inteligencias artificiales de manera correcta. ¿Pero qué les queda a las pequeñas empresas y a nosotros, el común de los mortales, que no tenemos la suerte de tener grandes fuentes de datos, hardware dedicado, o los recursos necesarios para hacer buenas inteligencias artificiales? Esto es lo que el equipo de Microsoft Research está tratando de resolver con su nuevo desarrollo.
Como muchos ya sabréis, el paradigma actual de la inteligencia artificial es el siguiente: los sistemas necesarios para hacer machine learning están altamente centralizados, y son propiedad de un número muy reducido de empresas. Las predicciones sobre sus modelos generalmente se venden en un modelo por transacción (si es que se ofrecen públicamente), y las colecciones de datos que utilizan para entrenar los sistemas son generalmente propietarios y caros —o imposibles— de recrear debido a la falta de acceso a fuentes de datos. Adicionalmente, los modelos ofrecidos de manera pública corren el riesgo de estar desactualizados si no se alimentan regularmente con datos para actualizar y re-entrenarlos (y como ya dijimos, no tenemos la suerte de tener acceso a grandes cantidades de datos para hacer esto).
Cuál es la propuesta de Microsoft para cambiar este paradigma? El uso de una inteligencia artificial descentralizada y colaborativa sobre blockchain. Esta idea no es nueva, y ya hay empresas que la están proponiendo, pero es la primera vez que esta propuesta viene por parte de uno de los grandes. A través de este nuevo sistema, “sus participantes son capaces de entrenar y mantener modelos de manera colaborativa, así como construir colecciones de datos sobre una plataforma de blockchain pública”.
¿Qué tiene que ver el blockchain con todo esto?
La tecnología blockchain ofrece dos cosas al sistema: confianza (olvídate de tener que depositar tu confianza sobre un sistema centralizado o una única compañía), y una forma sencilla de implementar de manera segura y confiable un sistema de incentivos que favorezca a que los usuarios contribuyan con sus datos y mejoren los modelos.
En el paradigma actual de la inteligencia artificial estamos generalmente utilizando servicios especializados centralizados en cloud que no controlamos ni sabemos como están siendo ejecutados, incluso cuando lo que se ejecuta es un modelo nuestro o software de código abierto. No sabemos qué pasa dentro de este sistema centralizado, y si se está incluyendo código adicional fuera de nuestro control. El uso de la tecnología blockchain ofrece un nivel de confianza y “responsabilidad” sobre el código que se ejecuta en la infraestructura. En la propuesta de Microsoft, los modelos públicos se despliegan sobre smart contracts para asegurar que se ejecutan acorde a las especificaciones determinadas en el momento de su creación. Así, un usuario podría actualizar el modelo “on-chain” a cambio de un pequeño coste de transacción, o hacerlo “off-chain” en su propio dispositivo, sin incurrir por tanto en ningún tipo de coste.
Este modelo abre la puerta a la resolución de una de las principales preocupaciones alrededor de la inteligencia artificial: la privacidad de los datos. Imagina que pudiese hacer uso de tu asistente personal preferido (Siri, Cortana, Alexa, Jarvis, etc.), y que pudieses elegir si utilizar su modelo público desplegado sobre una blockchain, en el que sabes como se están utilizando sus datos para actualizar el modelo, y en el que te beneficias de los datos aportados por otros usuarios del sistema; o que pudieras, como individuo paranoico de la privacidad que eres, y que no quiere utilizar un modelo público, descargarte del sistema un modelo base en tu dispositivo, entrenándolo exclusivamente de forma local con tu información personal (no sería tan preciso como el modelo público, donde todos los usuarios contribuyen a su mejora, pero es suficientemente privado para ti). Suena interesante, ¿verdad?
¿Como funciona el sistema?
Para empezar, el modelo que quiere ser usado se sube a la plataforma blockchain (implementado sobre un smart contract). En su implementación actual, Microsoft ha implementado un modelo de Perceptron simple para casos de uso como el análisis de sentimientos (no es fácil implementar modelos complejos sobre smart contracts todavía. Esto puede ser una línea de investigación interesante). Cuando se suben modelos a la blockchain, es mejor que estos tengan ya un nivel básico de entrenamiento, para que los usuarios sean capaces de obtener una precisión decente sin tener que esperar a varias rondas de entrenamiento. Con el modelo publicado en el sistema, los usuarios son capaces de añadir datos para re-entrenar el modelo, y hacer predicciones sobre el mismo utilizando su propios datos (ver figura siguiente).
Colaboración a través de incentivos
Microsoft propone una serie de sistemas de incentivos para fomentar que los usuarios contribuyan a los modelos para mantener y mejorar su rendimiento. Inicialmente, proponen tres tipos de modelos:
Gamificado: Este sistema de incentivos se basa en la voluntad por parte de la comunidad de contribuir a un bien común. A cambio de su contribución, los usuarios son recompensados con puntos, medallas o un tokens de utilidad (que puedan utilizar luego, por ejemplo, para hacer peticiones sobre el modelo).
Mercado de predicciones: Este es un enfoque más interesante. En este sistema de incentivos, los contribuidores son recompensados si sus datos mejoran el rendimiento del modelo. Este mecanismo se construye a partir del trabajo de una serie de papers, y se basan en el uso modelos criptoeconómicos (modelos que están “en la sangre” de los sistemas basados en blockchain) para favorecer a que los usuarios se comporten bien en el sistema. La siguiente figura representa de forma visual como se comporta este sistema de incentivos.
Autoevaluación continua: En este mecanismo los participantes pueden validar de manera efectiva, y pagar a otros por hacer buenas contribuciones. En este escenario, un modelo existente y ya entrenado es desplegado. Un contribuidor que quiera actualizar el modelo, envía la información pertinente, y genera un depósito relacionada con su actualización. Una vez haya pasado un tiempo predeterminado, si el modelo todavía se comporta bien ante peticiones de predicción, el usuario recupera su deposito. En este caso asumimos que los datos enviados han sido “buenos”, y su contribuidor obtiene un punto. Si por el contrario, el contribuidor añade datos “malos”, entonces el deposito de este contribuidor se reparte proporcionalmente entre todos los usuarios que hubieran ganado puntos aportando datos “buenos” al sistema.
¿Pero los smart contract no son sólo para código simple?
Lo sé, esto es probablemente una de las cosas que más te han chirriado leyendo el artículo, pero para responder a esta preguntar (que yo también tenía) voy a la respuesta del equipo “oficial” del equipo de Microsoft Research detrás del proyecto:
“There are many options. We can restrict the framework to simple models: Perceptron, Naive Bayes, Nearest Centroid, etc. We can also combine off-chain computation with on-chain computation in a few ways such as:
encoding off-chain to a higher dimensional representation and just have the final layers of the model fine-tuned on-chain,
using secure multiparty computation, or
using external APIs, or as they are called the blockchain space, oracles, to train and run the model
We can also use algorithms that do not require all models parameters to be updated (e.g. Perceptron). We hope to inspire more research in efficient ways to update more complex models.
Some of those proposals are not in the true spirit of this system which is to share models completely publicly but for some applications they may be suitable. At least the data would be shared so others can still use it to train their own models.”
Esto es un extracto que tiene ideas interesantes, y que me he tomado la libertad de acentuar para tu disfrute personal.
Conclusiones
Con este sistema, Microsoft pretende ofrecer un sistema para compartir modelos y contribuir de manera colaborativa a distintos modelos para mejorar su precisión y rendimiento. Es un buen primer paso (aunque quizás algo obvio) hacia la relación entre inteligencia artificial y blockchain. En mi opinión, este trabajo abre interesantes preguntar para seguir investigando:
¿Tiene sentido pensar en un lenguaje de programación de smart contracts más avanzado que permita la ejecución de modelos complejos e intensivos en recursos de inteligencia artificial distribuida complejos?
El hardware necesario para entrenar una inteligencia artificial es caro y escaso (solo unos pocos proveedores de cloud lo ofrecen). ¿Podemos, por tanto, implementar una forma de utilizar de manera indistinta y transparente todos los recursos público ofrecidos por cualquier proveedor cloud para entrenar nuestros modelos (de manera similar a como hacen empresas como iExec o Ankr)?
Y si acabamos utilizando hardware dedicado de otros, y a compartir datos con diferentes entidades, ¿cómo vamos a asegurar la privacidad de los datos? Aquí es donde entran en juego sistemas avanzados de criptografía (de las que puede que hable en unas semanas) como (y esto es algo que he decidido que no voy a traducir) secure multiparty computation (mencionado arriba), homomorphic encryption and zero-knowledge proofs; o el uso de técnicas de aprendizaje federado.
En definitiva, vamos a tener que estar muy atentos a ver qué pasa con esta nueva pareja. ¿Tendrán un final feliz? Y a vosotros, ¿se os ocurre algún caso de uso para el que la inteligencia artificial y el blockchain son una mezcla perfecta?