Google I/O'yu ayarladığınız için teşekkür ederiz. İsteğe bağlı olarak tüm oturumları görüntüleyin İsteğe bağlı olarak izleyin

Birleşik Öğrenim

genel bakış

Bu belge, birleştirilmiş eğitim veya TensorFlow'da uygulanan mevcut makine öğrenimi modelleriyle değerlendirme gibi birleştirilmiş öğrenme görevlerini kolaylaştıran arabirimleri tanıtmaktadır. Bu arayüzleri tasarlarken birincil amacımız, birleşik öğrenmeyi arka planda nasıl çalıştığına dair bilgi gerektirmeden deneyimlemeyi mümkün kılmak ve uygulanan birleşik öğrenme algoritmalarını çeşitli mevcut model ve veriler üzerinde değerlendirmekti. Platforma geri katkıda bulunmanızı öneririz. TFF, genişletilebilirlik ve şekillendirilebilirlik göz önünde bulundurularak tasarlanmıştır ve katkıları memnuniyetle karşılıyoruz; Neler bulduğunuzu görmek için heyecanlıyız!

Bu katman tarafından sunulan arayüzler aşağıdaki üç temel bölümden oluşur:

  • modeller Mevcut modellerinizi TFF ile kullanmak üzere sarmanıza izin veren sınıflar ve yardımcı işlevler. Bir modeli kaydırmak, tek bir sarma işlevini çağırmak (örn. tff.learning.models.from_keras_model ) veya tam özelleştirilebilirlik için tff.learning.models.VariableModel arabiriminin bir alt sınıfını tanımlamak kadar basit olabilir.

  • Birleşik Hesaplama Oluşturucuları . Mevcut modellerinizi kullanarak eğitim veya değerlendirme için birleştirilmiş hesaplamalar oluşturan yardımcı işlevler.

  • veri kümeleri Birleştirilmiş öğrenme senaryolarını simüle etmek için Python'da indirebileceğiniz ve erişebileceğiniz hazır veri koleksiyonları. Birleşik öğrenim, merkezi bir konumda kolayca indirilemeyen merkezi olmayan verilerle kullanılmak üzere tasarlanmış olsa da, araştırma ve geliştirme aşamalarında, yerel olarak indirilebilen ve değiştirilebilen verileri kullanarak ilk deneyleri yapmak, özellikle geliştiriciler için genellikle uygundur. yaklaşım için yeni.

Bu arabirimler, araştırma veri kümeleri ve tff.simulation içinde gruplandırılmış simülasyonla ilgili diğer yetenekler dışında, öncelikle tff.learning ad alanında tanımlanır. Bu katman, aynı zamanda bir çalıştırma ortamı da sağlayan Federated Core (FC) tarafından sunulan alt düzey arabirimler kullanılarak uygulanır.

Devam etmeden önce, burada açıklanan kavramların çoğunu somut örneklerle tanıttıklarından, görüntü sınıflandırma ve metin oluşturma ile ilgili eğitimleri incelemenizi öneririz. TFF'nin nasıl çalıştığı hakkında daha fazla bilgi edinmek istiyorsanız, birleştirilmiş hesaplamaların mantığını ifade etmek ve TFF'nin mevcut uygulamasını incelemek için kullandığımız alt düzey arayüzlere giriş olarak özel algoritmalar öğreticisine göz atmak isteyebilirsiniz. tff.learning arayüzleri.

modeller

Mimari varsayımlar

Serileştirme

TFF, yazdığınız makine öğrenimi modeli kodunun, çeşitli yeteneklere sahip çok sayıda heterojen istemci üzerinde yürütüldüğü çeşitli dağıtılmış öğrenme senaryolarını desteklemeyi amaçlar. Spektrumun bir ucunda, bazı uygulamalarda bu istemciler güçlü veritabanı sunucuları olabilirken, platformumuzun desteklemeyi amaçladığı birçok önemli kullanım, sınırlı kaynaklara sahip mobil ve gömülü cihazları içerir. Bu cihazların Python çalışma zamanlarını barındırabileceğini varsayamayız; Bu noktada varsayabileceğimiz tek şey, yerel bir TensorFlow çalışma zamanını barındırabilecek kapasitede olduklarıdır. Bu nedenle, TFF'de yaptığımız temel bir mimari varsayım, model kodunuzun bir TensorFlow grafiği olarak serileştirilebilir olması gerektiğidir.

İstek modunu kullanmak gibi en son en iyi uygulamaları izleyerek TF kodunuzu geliştirmeye devam edebilirsiniz (ve geliştirmelisiniz). Ancak, son kod seri hale getirilebilir olmalıdır (örneğin, istekli mod kodu için bir tf.function olarak sarılabilir). Bu, yürütme zamanında gerekli olan herhangi bir Python durumu veya kontrol akışının serileştirilebilmesini sağlar (muhtemelen Autograph'ın yardımıyla).

Şu anda TensorFlow, istekli mod TensorFlow'u seri hale getirmeyi ve serisini kaldırmayı tam olarak desteklememektedir. Bu nedenle, TFF'deki serileştirme şu anda tüm kodun TFF'nin kontrol ettiği bir tf.Graph içinde oluşturulması gereken TF 1.0 modelini takip eder. Bu, şu anda TFF'nin halihazırda oluşturulmuş bir modeli kullanamayacağı anlamına gelir; bunun yerine, model tanımı mantığı, bir tff.learning.models.VariableModel döndüren argsız bir işlevde paketlenmiştir. Bu işlev daha sonra modelin tüm bileşenlerinin serileştirilmesini sağlamak için TFF tarafından çağrılır. Ek olarak, türü kesin olarak belirlenmiş bir ortam olan TFF, modelinizin giriş türünün belirtilmesi gibi biraz ek meta veri gerektirecektir.

Toplama

Çoğu kullanıcının Keras kullanarak modeller oluşturmasını şiddetle tavsiye ediyoruz, aşağıdaki Keras için Dönüştürücüler bölümüne bakın. Bu sarmalayıcılar, model güncellemelerinin toplanmasını ve ayrıca model için otomatik olarak tanımlanan tüm ölçümleri işler. Ancak, genel bir tff.learning.models.VariableModel için toplamanın nasıl ele alındığını anlamak yine de yararlı olabilir.

Birleşik öğrenimde her zaman en az iki toplama katmanı vardır: yerel cihaz üstü toplama ve cihazlar arası (veya birleşik) toplama:

  • Yerel toplama . Bu toplama düzeyi, bireysel bir müşterinin sahip olduğu birden fazla örnek grubu genelinde toplamayı ifade eder. Hem model yerel olarak eğitildikçe sırayla gelişmeye devam eden model parametreleri (değişkenler) hem de modelinizin yerel olarak tekrar güncelleyeceği hesapladığınız istatistikler (ortalama kayıp, doğruluk ve diğer ölçümler gibi) için geçerlidir. her bir müşterinin yerel veri akışı üzerinde yinelenirken.

    Bu düzeyde toplama gerçekleştirmek, model kodunuzun sorumluluğundadır ve standart TensorFlow yapıları kullanılarak gerçekleştirilir.

    İşlemenin genel yapısı aşağıdaki gibidir:

    • Model önce toplu iş sayısı veya işlenen örnek sayısı, toplu iş başına veya örnek başına kayıpların toplamı gibi kümeleri tutmak için tf.Variable s'yi oluşturur.

    • TFF, bir yan etki olarak çeşitli kümeleri tutan değişkenleri güncellemenize olanak tanıyan müteakip müşteri verileri toplu işlerinde sırayla Model forward_pass yöntemini birden çok kez çağırır.

    • Son olarak TFF, modelinizin topladığı tüm özet istatistikleri müşteri tarafından dışa aktarılmak üzere kompakt bir metrik kümesi halinde derlemesine izin vermek için Modelinizde report_local_unfinalized_metrics yöntemini çağırır. Burası, örneğin, model kodunuzun, kayıpların toplamını, ortalama kaybı vb. dışa aktarmak için işlenen örneklerin sayısına bölebileceği yerdir.

  • Federe toplama . Bu toplama düzeyi, sistemdeki birden fazla istemci (cihaz) genelinde toplamayı ifade eder. Yine, hem istemciler arasında ortalaması alınan model parametreleri (değişkenler) hem de modelinizin yerel toplamanın bir sonucu olarak dışa aktardığı metrikler için geçerlidir.

    Bu seviyede kümeleme yapmak TFF'nin sorumluluğundadır. Bununla birlikte, bir model yaratıcısı olarak, bu süreci kontrol edebilirsiniz (bununla ilgili daha fazlası aşağıda).

    İşlemenin genel yapısı aşağıdaki gibidir:

    • İlk model ve eğitim için gereken tüm parametreler, bir sunucu tarafından bir eğitim veya değerlendirme turuna katılacak olan bir müşteri alt kümesine dağıtılır.

    • Her istemcide, bağımsız ve paralel olarak, model kodunuz, yukarıda açıklandığı gibi (eğitim sırasında) yeni bir model parametreleri seti ve yeni bir yerel ölçüm seti oluşturmak için bir yerel veri toplu akışı akışında tekrar tekrar çağrılır (bu yereldir). toplama).

    • TFF, sistem genelinde model parametrelerini ve yerel olarak dışa aktarılan ölçümleri toplamak ve toplamak için dağıtılmış bir toplama protokolü çalıştırır. Bu mantık, TFF'nin kendi birleşik hesaplama dili (TensorFlow'da değil) kullanılarak bildirimsel bir şekilde ifade edilir. Toplama API'si hakkında daha fazla bilgi için özel algoritmalar öğreticisine bakın.

Soyut arayüzler

Bu temel oluşturucu + meta veri arayüzü, aşağıdaki gibi tff.learning.models.VariableModel arayüzü ile temsil edilir:

  • Yapıcı, forward_pass ve report_local_unfinalized_metrics yöntemleri, sırasıyla raporlamak istediğiniz model değişkenlerini, iletme geçişini ve istatistikleri oluşturmalıdır. Bu yöntemlerle oluşturulan TensorFlow, yukarıda tartışıldığı gibi seri hale getirilebilir olmalıdır.

  • Eğitilebilir, eğitilemez ve yerel değişkenlerinizin alt kümelerini döndüren 3 özelliğin yanı sıra input_spec özelliği meta verileri temsil eder. TFF bu bilgiyi, modelinizin parçalarının birleştirilmiş optimizasyon algoritmalarına nasıl bağlanacağını belirlemek ve oluşturulan sistemin doğruluğunu doğrulamaya yardımcı olacak dahili tip imzaları tanımlamak için kullanır (böylece modeliniz, birbiriyle eşleşmeyen veriler üzerinden başlatılamaz). model tüketmek için tasarlanmıştır).

Ek olarak, tff.learning.models.VariableModel soyut arabirimi, bir metriğin nihaileştirilmemiş değerlerini alan ( report_local_unfinalized_metrics() tarafından döndürülen) ve nihaileştirilmiş metrik değerlerini döndüren bir metric_finalizers özelliğini gösterir. metric_finalizers ve report_local_unfinalized_metrics() yöntemi, birleştirilmiş eğitim süreçlerini veya değerlendirme hesaplamalarını tanımlarken müşteriler arası bir metrik toplayıcı oluşturmak için birlikte kullanılacaktır. Örneğin, basit bir tff.learning.metrics.sum_then_finalize toplayıcı, önce istemcilerden gelen sonlandırılmamış metrik değerlerini toplar ve ardından sunucudaki sonlandırıcı işlevlerini çağırır.

Kendi özel tff.learning.models.VariableModel nasıl tanımlayacağınıza ilişkin örnekleri görüntü sınıflandırma eğitimimizin ikinci bölümünde ve ayrıca model_examples.py içinde test etmek için kullandığımız örnek modellerde bulabilirsiniz.

Keras için Dönüştürücüler

TFF'nin ihtiyaç duyduğu neredeyse tüm bilgiler tf.keras arabirimleri çağrılarak elde edilebilir, dolayısıyla bir Keras modeliniz varsa, bir tff.learning.models.VariableModel tff.learning.models.from_keras_model .

TFF'nin hala bir oluşturucu - aşağıdaki gibi bağımsız değişken olmayan bir model işlevi - sağlamanızı istediğini unutmayın:

def model_fn():
  keras_model = ...
  return tff.learning.models.from_keras_model(keras_model, sample_batch, loss=...)

Modelin kendisine ek olarak, modelinizin girişinin türünü ve şeklini belirlemek için TFF'nin kullandığı örnek bir veri grubu sağlarsınız. Bu, TFF'nin istemci cihazlarda fiilen mevcut olacak veriler için modeli düzgün bir şekilde başlatabilmesini sağlar (çünkü bu verilerin, seri hale getirilecek TensorFlow'u oluştururken genellikle mevcut olmadığını varsayıyoruz).

Keras sarmalayıcıların kullanımı , görüntü sınıflandırma ve metin oluşturma eğitimlerimizde gösterilmektedir.

Birleşik Hesaplama Oluşturucuları

tff.learning paketi, öğrenmeyle ilgili görevleri gerçekleştiren tff.Computation s için birkaç oluşturucu sağlar; bu tür hesaplamaların gelecekte genişlemesini bekliyoruz.

Mimari varsayımlar

Uygulamak

Birleşik bir hesaplamayı çalıştırmanın iki farklı aşaması vardır.

  • Derleme : TFF, ilk önce birleştirilmiş öğrenme algoritmalarını tüm dağıtılmış hesaplamanın soyut bir serileştirilmiş temsilinde derler . Bu, TensorFlow serileştirmenin gerçekleştiği zamandır, ancak daha verimli yürütmeyi desteklemek için başka dönüşümler gerçekleşebilir. Derleyici tarafından yayınlanan seri hale getirilmiş temsili birleşik bir hesaplama olarak adlandırırız.

  • Execute TFF, bu hesaplamaları yürütmek için yollar sağlar. Şimdilik yürütme yalnızca yerel bir simülasyon yoluyla destekleniyor (örn. simüle edilmiş merkezi olmayan verileri kullanan bir not defterinde).

Birleştirilmiş model ortalamasını kullanan bir eğitim algoritması veya birleştirilmiş bir değerlendirme gibi TFF'nin Birleşik Öğrenim API'si tarafından oluşturulan birleştirilmiş bir hesaplama, bir dizi öğe içerir, en önemlisi:

  • Modelinizin eğitim/değerlendirme döngüsünü yürütmek için Federated Learning çerçevesi tarafından oluşturulan ek TensorFlow kodunun yanı sıra model kodunuzun seri hale getirilmiş bir formu (optimizasyon araçları oluşturma, model güncellemelerini uygulama, tf.data.Dataset s üzerinde yineleme ve hesaplama ölçümleri, ve birkaç isim vermek gerekirse, toplu güncellemenin sunucuda uygulanması).

  • İstemciler ve bir sunucu arasındaki iletişimin (tipik olarak istemci aygıtları arasında çeşitli toplama biçimleri ve sunucudan tüm istemcilere yayın ) ve bu dağıtılmış iletişimin istemci-yerel veya sunucu-yerel yürütme ile nasıl serpiştirildiğine ilişkin bildirimsel bir belirtim TensorFlow kodunun.

Bu seri hale getirilmiş formda temsil edilen birleştirilmiş hesaplamalar, Python'dan farklı, platformdan bağımsız bir dahili dilde ifade edilir, ancak Birleşik Öğrenme API'sini kullanmak için bu temsilin ayrıntılarıyla ilgilenmeniz gerekmez. Hesaplamalar, Python kodunuzda tff.Computation türünde nesneler olarak temsil edilir ve bunları çoğunlukla opak Python callable s olarak değerlendirebilirsiniz.

Öğreticilerde, bu birleştirilmiş hesaplamaları, yerel olarak yürütülecek normal Python işlevleriymiş gibi çağıracaksınız. Bununla birlikte TFF, birleşik hesaplamaları yürütme ortamının çoğu yönünden bağımsız bir şekilde ifade etmek üzere tasarlanmıştır, böylece potansiyel olarak örneğin Android çalıştıran cihaz gruplarına veya bir veri merkezindeki kümelere konuşlandırılabilirler. Yine, bunun ana sonucu serileştirmeyle ilgili güçlü varsayımlardır. Özellikle, aşağıda açıklanan build_... yöntemlerinden birini çağırdığınızda, hesaplama tamamen seri hale getirilir.

modelleme durumu

TFF, işlevsel bir programlama ortamıdır, ancak birleştirilmiş öğrenmeye ilişkin pek çok süreç durum bilgilidir. Örneğin, birden çok birleşik model ortalamasını içeren bir eğitim döngüsü, durum bilgisi olan bir süreç olarak sınıflandırabileceğimiz bir örnektir. Bu süreçte, döngüden döngüye gelişen durum, eğitilmekte olan model parametreleri kümesini ve muhtemelen optimize edici ile ilişkili ek durumu (örneğin, bir momentum vektörü) içerir.

TFF işlevsel olduğu için, durum bilgisi olan süreçler, TFF'de mevcut durumu bir girdi olarak kabul eden ve ardından güncel durumu bir çıktı olarak sağlayan hesaplamalar olarak modellenir. Durum bilgisi olan bir süreci tam olarak tanımlamak için, ilk durumun nereden geldiğini de belirtmek gerekir (aksi takdirde süreci önyükleyemeyiz). Bu, tff.templates.IterativeProcess yardımcı sınıfının tanımında yakalanır ve next initialize ve yinelemeye karşılık gelen 2 özellik ile birlikte

Mevcut inşaatçılar

Şu anda TFF, birleştirilmiş eğitim ve değerlendirme için birleştirilmiş hesaplamalar oluşturan çeşitli oluşturucu işlevleri sunmaktadır. Dikkate değer iki örnek şunları içerir:

veri kümeleri

Mimari varsayımlar

müşteri seçimi

Tipik birleşik öğrenme senaryosunda, potansiyel olarak yüz milyonlarca istemci cihazından oluşan büyük bir popülasyona sahibiz ve bunların yalnızca küçük bir kısmı aktif olabilir ve herhangi bir anda eğitim için kullanılabilir olabilir (örneğin, bu, şu istemcilerle sınırlı olabilir: bir güç kaynağına takılı, ölçülü bir ağda değil ve başka türlü boşta). Genel olarak, eğitime veya değerlendirmeye katılmak için uygun müşteri grubu, geliştiricinin kontrolü dışındadır. Ayrıca, milyonlarca müşteriyi koordine etmek pratik olmadığından, tipik bir eğitim veya değerlendirme turu, rastgele örneklenebilecek mevcut müşterilerin yalnızca bir kısmını içerecektir.

Bunun en önemli sonucu, birleştirilmiş hesaplamaların, tasarım gereği, kesin katılımcı grubundan habersiz bir şekilde ifade edilmesidir; tüm işlemler, anonim istemcilerden oluşan soyut bir grup üzerinde toplu işlemler olarak ifade edilir ve bu grup, bir eğitim turundan diğerine değişiklik gösterebilir. Hesaplamanın somut katılımcılara ve dolayısıyla hesaplamaya besledikleri somut verilere gerçek bağlanması, bu nedenle hesaplamanın kendisinin dışında modellenir.

Federe öğrenme kodunuzun gerçekçi bir dağıtımını simüle etmek için genellikle şuna benzeyen bir eğitim döngüsü yazarsınız:

trainer = tff.learning.algorithms.build_weighted_fed_avg(...)
state = trainer.initialize()
federated_training_data = ...

def sample(federate_data):
  return ...

while True:
  data_for_this_round = sample(federated_training_data)
  result = trainer.next(state, data_for_this_round)
  state = result.state

Bunu kolaylaştırmak için, simülasyonlarda TFF kullanılırken, birleşik veriler Python list olarak kabul edilir ve katılan istemci cihaz başına bir öğe o cihazın yerel tf.data.Dataset temsil eder.

Soyut arayüzler

Simüle edilmiş birleştirilmiş veri kümeleriyle çalışmayı standart hale getirmek için TFF, istemci kümesini numaralandırmaya ve belirli bir istemcinin verilerini içeren bir tf.data.Dataset oluşturmaya izin veren soyut bir tff.simulation.datasets.ClientData arabirimi sağlar. müşteri. Bu tf.data.Dataset s, istekli modda oluşturulan birleşik hesaplamalara doğrudan girdi olarak beslenebilir.

İstemci kimliklerine erişme yeteneğinin, yalnızca veri kümeleri tarafından, belirli istemci alt kümelerinden gelen veriler üzerinde eğitim yeteneğinin gerekli olabileceği simülasyonlarda kullanım için sağlanan bir özellik olduğu unutulmamalıdır (örn. müşteri türleri). Derlenen hesaplamalar ve altta yatan çalışma zamanı, herhangi bir müşteri kimliği kavramı içermez . İstemcilerin belirli bir alt kümesindeki veriler girdi olarak seçildikten sonra, örneğin tff.templates.IterativeProcess.next çağrısında, istemci kimlikleri artık içinde görünmez.

Mevcut veri setleri

Simülasyonlarda kullanılmak üzere tff.simulation.datasets.ClientData arabirimini uygulayan veri kümeleri için tff.simulation.datasets ad alanını ayırdık ve görüntü sınıflandırmasını ve metin oluşturma eğitimlerini desteklemek için veri kümeleriyle tohumladık. Platforma kendi veri kümelerinizle katkıda bulunmanızı teşvik etmek isteriz.

,

genel bakış

Bu belge, birleştirilmiş eğitim veya TensorFlow'da uygulanan mevcut makine öğrenimi modelleriyle değerlendirme gibi birleştirilmiş öğrenme görevlerini kolaylaştıran arabirimleri tanıtmaktadır. Bu arayüzleri tasarlarken birincil amacımız, birleşik öğrenmeyi arka planda nasıl çalıştığına dair bilgi gerektirmeden deneyimlemeyi mümkün kılmak ve uygulanan birleşik öğrenme algoritmalarını çeşitli mevcut model ve veriler üzerinde değerlendirmekti. Platforma geri katkıda bulunmanızı öneririz. TFF, genişletilebilirlik ve şekillendirilebilirlik göz önünde bulundurularak tasarlanmıştır ve katkıları memnuniyetle karşılıyoruz; Neler bulduğunuzu görmek için heyecanlıyız!

Bu katman tarafından sunulan arayüzler aşağıdaki üç temel bölümden oluşur:

  • modeller Mevcut modellerinizi TFF ile kullanmak üzere sarmanıza izin veren sınıflar ve yardımcı işlevler. Bir modeli kaydırmak, tek bir sarma işlevini çağırmak (örn. tff.learning.models.from_keras_model ) veya tam özelleştirilebilirlik için tff.learning.models.VariableModel arabiriminin bir alt sınıfını tanımlamak kadar basit olabilir.

  • Birleşik Hesaplama Oluşturucuları . Mevcut modellerinizi kullanarak eğitim veya değerlendirme için birleştirilmiş hesaplamalar oluşturan yardımcı işlevler.

  • veri kümeleri Birleştirilmiş öğrenme senaryolarını simüle etmek için Python'da indirebileceğiniz ve erişebileceğiniz hazır veri koleksiyonları. Birleşik öğrenim, merkezi bir konumda kolayca indirilemeyen merkezi olmayan verilerle kullanılmak üzere tasarlanmış olsa da, araştırma ve geliştirme aşamalarında, yerel olarak indirilebilen ve değiştirilebilen verileri kullanarak ilk deneyleri yapmak, özellikle geliştiriciler için genellikle uygundur. yaklaşım için yeni.

Bu arabirimler, araştırma veri kümeleri ve tff.simulation içinde gruplandırılmış simülasyonla ilgili diğer yetenekler dışında, öncelikle tff.learning ad alanında tanımlanır. Bu katman, aynı zamanda bir çalıştırma ortamı da sağlayan Federated Core (FC) tarafından sunulan alt düzey arabirimler kullanılarak uygulanır.

Devam etmeden önce, burada açıklanan kavramların çoğunu somut örneklerle tanıttıklarından, görüntü sınıflandırma ve metin oluşturma ile ilgili eğitimleri incelemenizi öneririz. TFF'nin nasıl çalıştığı hakkında daha fazla bilgi edinmek istiyorsanız, birleştirilmiş hesaplamaların mantığını ifade etmek ve TFF'nin mevcut uygulamasını incelemek için kullandığımız alt düzey arayüzlere giriş olarak özel algoritmalar öğreticisine göz atmak isteyebilirsiniz. tff.learning arayüzleri.

modeller

Mimari varsayımlar

Serileştirme

TFF, yazdığınız makine öğrenimi modeli kodunun, çeşitli yeteneklere sahip çok sayıda heterojen istemci üzerinde yürütüldüğü çeşitli dağıtılmış öğrenme senaryolarını desteklemeyi amaçlar. Spektrumun bir ucunda, bazı uygulamalarda bu istemciler güçlü veritabanı sunucuları olabilirken, platformumuzun desteklemeyi amaçladığı birçok önemli kullanım, sınırlı kaynaklara sahip mobil ve gömülü cihazları içerir. Bu cihazların Python çalışma zamanlarını barındırabileceğini varsayamayız; Bu noktada varsayabileceğimiz tek şey, yerel bir TensorFlow çalışma zamanını barındırabilecek kapasitede olduklarıdır. Bu nedenle, TFF'de yaptığımız temel bir mimari varsayım, model kodunuzun bir TensorFlow grafiği olarak serileştirilebilir olması gerektiğidir.

İstek modunu kullanmak gibi en son en iyi uygulamaları izleyerek TF kodunuzu geliştirmeye devam edebilirsiniz (ve geliştirmelisiniz). Ancak, son kod seri hale getirilebilir olmalıdır (örneğin, istekli mod kodu için bir tf.function olarak sarılabilir). Bu, yürütme zamanında gerekli olan herhangi bir Python durumu veya kontrol akışının serileştirilebilmesini sağlar (muhtemelen Autograph'ın yardımıyla).

Şu anda TensorFlow, istekli mod TensorFlow'u seri hale getirmeyi ve serisini kaldırmayı tam olarak desteklememektedir. Bu nedenle, TFF'deki serileştirme şu anda tüm kodun TFF'nin kontrol ettiği bir tf.Graph içinde oluşturulması gereken TF 1.0 modelini takip eder. Bu, şu anda TFF'nin halihazırda oluşturulmuş bir modeli kullanamayacağı anlamına gelir; bunun yerine, model tanımı mantığı, bir tff.learning.models.VariableModel döndüren argsız bir işlevde paketlenmiştir. Bu işlev daha sonra modelin tüm bileşenlerinin serileştirilmesini sağlamak için TFF tarafından çağrılır. Ek olarak, türü kesin olarak belirlenmiş bir ortam olan TFF, modelinizin giriş türünün belirtilmesi gibi biraz ek meta veri gerektirecektir.

Toplama

Çoğu kullanıcının Keras kullanarak modeller oluşturmasını şiddetle tavsiye ediyoruz, aşağıdaki Keras için Dönüştürücüler bölümüne bakın. Bu sarmalayıcılar, model güncellemelerinin toplanmasını ve ayrıca model için otomatik olarak tanımlanan tüm ölçümleri işler. Ancak, genel bir tff.learning.models.VariableModel için toplamanın nasıl ele alındığını anlamak yine de yararlı olabilir.

Birleşik öğrenimde her zaman en az iki toplama katmanı vardır: yerel cihaz üstü toplama ve cihazlar arası (veya birleşik) toplama:

  • Yerel toplama . Bu toplama düzeyi, bireysel bir müşterinin sahip olduğu birden fazla örnek grubu genelinde toplamayı ifade eder. Hem model yerel olarak eğitildikçe sırayla gelişmeye devam eden model parametreleri (değişkenler) hem de modelinizin yerel olarak tekrar güncelleyeceği hesapladığınız istatistikler (ortalama kayıp, doğruluk ve diğer ölçümler gibi) için geçerlidir. her bir müşterinin yerel veri akışı üzerinde yinelenirken.

    Bu düzeyde toplama gerçekleştirmek, model kodunuzun sorumluluğundadır ve standart TensorFlow yapıları kullanılarak gerçekleştirilir.

    İşlemenin genel yapısı aşağıdaki gibidir:

    • Model önce toplu iş sayısı veya işlenen örnek sayısı, toplu iş başına veya örnek başına kayıpların toplamı gibi kümeleri tutmak için tf.Variable s'yi oluşturur.

    • TFF, bir yan etki olarak çeşitli kümeleri tutan değişkenleri güncellemenize olanak tanıyan müteakip müşteri verileri toplu işlerinde sırayla Model forward_pass yöntemini birden çok kez çağırır.

    • Son olarak TFF, modelinizin topladığı tüm özet istatistikleri müşteri tarafından dışa aktarılmak üzere kompakt bir metrik kümesi halinde derlemesine izin vermek için Modelinizde report_local_unfinalized_metrics yöntemini çağırır. Burası, örneğin, model kodunuzun, kayıpların toplamını, ortalama kaybı vb. dışa aktarmak için işlenen örneklerin sayısına bölebileceği yerdir.

  • Federe toplama . Bu toplama düzeyi, sistemdeki birden fazla istemci (cihaz) genelinde toplamayı ifade eder. Yine, hem istemciler arasında ortalaması alınan model parametreleri (değişkenler) hem de modelinizin yerel toplamanın bir sonucu olarak dışa aktardığı metrikler için geçerlidir.

    Bu seviyede kümeleme yapmak TFF'nin sorumluluğundadır. Bununla birlikte, bir model yaratıcısı olarak, bu süreci kontrol edebilirsiniz (bununla ilgili daha fazlası aşağıda).

    İşlemenin genel yapısı aşağıdaki gibidir:

    • İlk model ve eğitim için gereken tüm parametreler, bir sunucu tarafından bir eğitim veya değerlendirme turuna katılacak olan bir müşteri alt kümesine dağıtılır.

    • Her istemcide, bağımsız ve paralel olarak, model kodunuz, yukarıda açıklandığı gibi (eğitim sırasında) yeni bir model parametreleri seti ve yeni bir yerel ölçüm seti oluşturmak için bir yerel veri toplu akışı akışında tekrar tekrar çağrılır (bu yereldir). toplama).

    • TFF, sistem genelinde model parametrelerini ve yerel olarak dışa aktarılan ölçümleri toplamak ve toplamak için dağıtılmış bir toplama protokolü çalıştırır. Bu mantık, TFF'nin kendi birleşik hesaplama dili (TensorFlow'da değil) kullanılarak bildirimsel bir şekilde ifade edilir. Toplama API'si hakkında daha fazla bilgi için özel algoritmalar öğreticisine bakın.

Soyut arayüzler

Bu temel oluşturucu + meta veri arayüzü, aşağıdaki gibi tff.learning.models.VariableModel arayüzü ile temsil edilir:

  • Yapıcı, forward_pass ve report_local_unfinalized_metrics yöntemleri, sırasıyla raporlamak istediğiniz model değişkenlerini, iletme geçişini ve istatistikleri oluşturmalıdır. Bu yöntemlerle oluşturulan TensorFlow, yukarıda tartışıldığı gibi seri hale getirilebilir olmalıdır.

  • Eğitilebilir, eğitilemez ve yerel değişkenlerinizin alt kümelerini döndüren 3 özelliğin yanı sıra input_spec özelliği meta verileri temsil eder. TFF bu bilgiyi, modelinizin parçalarının birleştirilmiş optimizasyon algoritmalarına nasıl bağlanacağını belirlemek ve oluşturulan sistemin doğruluğunu doğrulamaya yardımcı olacak dahili tip imzaları tanımlamak için kullanır (böylece modeliniz, birbiriyle eşleşmeyen veriler üzerinden başlatılamaz). model tüketmek için tasarlanmıştır).

Ek olarak, tff.learning.models.VariableModel soyut arabirimi, bir metriğin nihaileştirilmemiş değerlerini alan ( report_local_unfinalized_metrics() tarafından döndürülen) ve nihaileştirilmiş metrik değerlerini döndüren bir metric_finalizers özelliğini gösterir. metric_finalizers ve report_local_unfinalized_metrics() yöntemi, birleştirilmiş eğitim süreçlerini veya değerlendirme hesaplamalarını tanımlarken müşteriler arası bir metrik toplayıcı oluşturmak için birlikte kullanılacaktır. Örneğin, basit bir tff.learning.metrics.sum_then_finalize toplayıcı, önce istemcilerden gelen sonlandırılmamış metrik değerlerini toplar ve ardından sunucudaki sonlandırıcı işlevlerini çağırır.

Kendi özel tff.learning.models.VariableModel nasıl tanımlayacağınıza ilişkin örnekleri görüntü sınıflandırma eğitimimizin ikinci bölümünde ve ayrıca model_examples.py içinde test etmek için kullandığımız örnek modellerde bulabilirsiniz.

Keras için Dönüştürücüler

TFF'nin ihtiyaç duyduğu neredeyse tüm bilgiler tf.keras arabirimleri çağrılarak elde edilebilir, dolayısıyla bir Keras modeliniz varsa, bir tff.learning.models.VariableModel tff.learning.models.from_keras_model .

TFF'nin hala bir oluşturucu - aşağıdaki gibi bağımsız değişken olmayan bir model işlevi - sağlamanızı istediğini unutmayın:

def model_fn():
  keras_model = ...
  return tff.learning.models.from_keras_model(keras_model, sample_batch, loss=...)

Modelin kendisine ek olarak, modelinizin girişinin türünü ve şeklini belirlemek için TFF'nin kullandığı örnek bir veri grubu sağlarsınız. Bu, TFF'nin istemci cihazlarda fiilen mevcut olacak veriler için modeli düzgün bir şekilde başlatabilmesini sağlar (çünkü bu verilerin, seri hale getirilecek TensorFlow'u oluştururken genellikle mevcut olmadığını varsayıyoruz).

Keras sarmalayıcıların kullanımı , görüntü sınıflandırma ve metin oluşturma eğitimlerimizde gösterilmektedir.

Birleşik Hesaplama Oluşturucuları

tff.learning paketi, öğrenmeyle ilgili görevleri gerçekleştiren tff.Computation s için birkaç oluşturucu sağlar; bu tür hesaplamaların gelecekte genişlemesini bekliyoruz.

Mimari varsayımlar

Uygulamak

Birleşik bir hesaplamayı çalıştırmanın iki farklı aşaması vardır.

  • Derleme : TFF, ilk önce birleştirilmiş öğrenme algoritmalarını tüm dağıtılmış hesaplamanın soyut bir serileştirilmiş temsilinde derler . Bu, TensorFlow serileştirmenin gerçekleştiği zamandır, ancak daha verimli yürütmeyi desteklemek için başka dönüşümler gerçekleşebilir. Derleyici tarafından yayınlanan seri hale getirilmiş temsili birleşik bir hesaplama olarak adlandırırız.

  • Execute TFF, bu hesaplamaları yürütmek için yollar sağlar. Şimdilik yürütme yalnızca yerel bir simülasyon yoluyla destekleniyor (örn. simüle edilmiş merkezi olmayan verileri kullanan bir not defterinde).

Birleştirilmiş model ortalamasını kullanan bir eğitim algoritması veya birleştirilmiş bir değerlendirme gibi TFF'nin Birleşik Öğrenim API'si tarafından oluşturulan birleştirilmiş bir hesaplama, bir dizi öğe içerir, en önemlisi:

  • Modelinizin eğitim/değerlendirme döngüsünü yürütmek için Federated Learning çerçevesi tarafından oluşturulan ek TensorFlow kodunun yanı sıra model kodunuzun seri hale getirilmiş bir formu (optimizasyon araçları oluşturma, model güncellemelerini uygulama, tf.data.Dataset s üzerinde yineleme ve hesaplama ölçümleri, ve birkaç isim vermek gerekirse, toplu güncellemenin sunucuda uygulanması).

  • İstemciler ve bir sunucu arasındaki iletişimin (tipik olarak istemci aygıtları arasında çeşitli toplama biçimleri ve sunucudan tüm istemcilere yayın ) ve bu dağıtılmış iletişimin istemci-yerel veya sunucu-yerel yürütme ile nasıl serpiştirildiğine ilişkin bildirimsel bir belirtim TensorFlow kodunun.

Bu seri hale getirilmiş formda temsil edilen birleştirilmiş hesaplamalar, Python'dan farklı, platformdan bağımsız bir dahili dilde ifade edilir, ancak Birleşik Öğrenme API'sini kullanmak için bu temsilin ayrıntılarıyla ilgilenmeniz gerekmez. Hesaplamalar, Python kodunuzda tff.Computation türünde nesneler olarak temsil edilir ve bunları çoğunlukla opak Python callable s olarak değerlendirebilirsiniz.

Öğreticilerde, bu birleştirilmiş hesaplamaları, yerel olarak yürütülecek normal Python işlevleriymiş gibi çağıracaksınız. Bununla birlikte TFF, birleşik hesaplamaları yürütme ortamının çoğu yönünden bağımsız bir şekilde ifade etmek üzere tasarlanmıştır, böylece potansiyel olarak örneğin Android çalıştıran cihaz gruplarına veya bir veri merkezindeki kümelere konuşlandırılabilirler. Yine, bunun ana sonucu serileştirmeyle ilgili güçlü varsayımlardır. Özellikle, aşağıda açıklanan build_... yöntemlerinden birini çağırdığınızda, hesaplama tamamen seri hale getirilir.

modelleme durumu

TFF, işlevsel bir programlama ortamıdır, ancak birleştirilmiş öğrenmeye ilişkin pek çok süreç durum bilgilidir. Örneğin, birden çok birleşik model ortalamasını içeren bir eğitim döngüsü, durum bilgisi olan bir süreç olarak sınıflandırabileceğimiz bir örnektir. Bu süreçte, döngüden döngüye gelişen durum, eğitilmekte olan model parametreleri kümesini ve muhtemelen optimize edici ile ilişkili ek durumu (örneğin, bir momentum vektörü) içerir.

TFF işlevsel olduğu için, durum bilgisi olan süreçler, TFF'de mevcut durumu bir girdi olarak kabul eden ve ardından güncel durumu bir çıktı olarak sağlayan hesaplamalar olarak modellenir. Durum bilgisi olan bir süreci tam olarak tanımlamak için, ilk durumun nereden geldiğini de belirtmek gerekir (aksi takdirde süreci önyükleyemeyiz). Bu, tff.templates.IterativeProcess yardımcı sınıfının tanımında yakalanır ve next initialize ve yinelemeye karşılık gelen 2 özellik ile birlikte

Mevcut inşaatçılar

At the moment, TFF provides various builder functions that generate federated computations for federated training and evaluation. Two notable examples include:

Datasets

Architectural assumptions

Client selection

In the typical federated learning scenario, we have a large population of potentially hundreds of millions of client devices, of which only a small portion may be active and available for training at any given moment (for example, this may be limited to clients that are plugged in to a power source, not on a metered network, and otherwise idle). Generally, the set of clients available to participate in training or evaluation is outside of the developer's control. Furthermore, as it's impractical to coordinate millions of clients, a typical round of training or evaluation will include only a fraction of the available clients, which may be sampled at random .

The key consequence of this is that federated computations, by design, are expressed in a manner that is oblivious to the exact set of participants; all processing is expressed as aggregate operations on an abstract group of anonymous clients , and that group might vary from one round of training to another. The actual binding of the computation to the concrete participants, and thus to the concrete data they feed into the computation, is thus modeled outside of the computation itself.

In order to simulate a realistic deployment of your federated learning code, you will generally write a training loop that looks like this:

trainer = tff.learning.algorithms.build_weighted_fed_avg(...)
state = trainer.initialize()
federated_training_data = ...

def sample(federate_data):
  return ...

while True:
  data_for_this_round = sample(federated_training_data)
  result = trainer.next(state, data_for_this_round)
  state = result.state

In order to facilitate this, when using TFF in simulations, federated data is accepted as Python list s, with one element per participating client device to represent that device's local tf.data.Dataset .

Abstract interfaces

In order to standardize dealing with simulated federated data sets, TFF provides an abstract interface tff.simulation.datasets.ClientData , which allows one to enumerate the set of clients, and to construct a tf.data.Dataset that contains the data of a particular client. Those tf.data.Dataset s can be fed directly as input to the generated federated computations in eager mode.

It should be noted that the ability to access client identities is a feature that's only provided by the datasets for use in simulations, where the ability to train on data from specific subsets of clients may be needed (eg, to simulate the diurnal availability of different types of clients). The compiled computations and the underlying runtime do not involve any notion of client identity. Once data from a specific subset of clients has been selected as an input, eg, in a call to tff.templates.IterativeProcess.next , client identities no longer appear in it.

Available data sets

We have dedicated the namespace tff.simulation.datasets for datasets that implement the tff.simulation.datasets.ClientData interface for use in simulations, and seeded it with datasets to support the image classification and text generation tutorials. We'd like to encourage you to contribute your own datasets to the platform.

,

Overview

This document introduces interfaces that facilitate federated learning tasks, such as federated training or evaluation with existing machine learning models implemented in TensorFlow. In designing these interfaces, our primary goal was to make it possible to experiment with federated learning without requiring the knowledge of how it works under the hood, and to evaluate the implemented federated learning algorithms on a variety of existing models and data. We encourage you to contribute back to the platform. TFF has been designed with extensibility and composability in mind, and we welcome contributions; we are excited to see what you come up with!

The interfaces offered by this layer consist of the following three key parts:

  • Models . Classes and helper functions that allow you to wrap your existing models for use with TFF. Wrapping a model can be as simple as calling a single wrapping function (eg, tff.learning.models.from_keras_model ), or defining a subclass of the tff.learning.models.VariableModel interface for full customizability.

  • Federated Computation Builders . Helper functions that construct federated computations for training or evaluation, using your existing models.

  • Datasets . Canned collections of data that you can download and access in Python for use in simulating federated learning scenarios. Although federated learning is designed for use with decentralized data that cannot be simply downloaded at a centralized location, at the research and development stages it is often convenient to conduct initial experiments using data that can be downloaded and manipulated locally, especially for developers who might be new to the approach.

These interfaces are defined primarily in the tff.learning namespace, except for research data sets and other simulation-related capabilities that have been grouped in tff.simulation . This layer is implemented using lower-level interfaces offered by the Federated Core (FC) , which also provides a runtime environment.

Before proceeding, we recommend that you first review the tutorials on image classification and text generation , as they introduce most of the concepts described here using concrete examples. If you're interested in learning more about how TFF works, you may want to skim over the custom algorithms tutorial as an introduction to the lower-level interfaces we use to express the logic of federated computations, and to study the existing implementation of the tff.learning interfaces.

Models

Architectural assumptions

Serialization

TFF aims at supporting a variety of distributed learning scenarios in which the machine learning model code you write might be executing on a large number of heterogeneous clients with diverse capabilities. While at one end of the spectrum, in some applications those clients might be powerful database servers, many important uses our platform intends to support involve mobile and embedded devices with limited resources. We cannot assume that these devices are capable of hosting Python runtimes; the only thing we can assume at this point is that they are capable of hosting a local TensorFlow runtime. Thus, a fundamental architectural assumption we make in TFF is that your model code must be serializable as a TensorFlow graph.

You can (and should) still develop your TF code following the latest best practices like using eager mode. However, the final code must be serializable (eg, can be wrapped as a tf.function for eager-mode code). This ensures that any Python state or control flow necessary at execution time can be serialized (possibly with the help of Autograph ).

Currently, TensorFlow does not fully support serializing and deserializing eager-mode TensorFlow. Thus, serialization in TFF currently follows the TF 1.0 pattern, where all code must be constructed inside a tf.Graph that TFF controls. This means currently TFF cannot consume an already-constructed model; instead, the model definition logic is packaged in a no-arg function that returns a tff.learning.models.VariableModel . This function is then called by TFF to ensure all components of the model are serialized. In addition, being a strongly-typed environment, TFF will require a little bit of additional metadata , such as a specification of your model's input type.

Aggregation

We strongly recommend most users construct models using Keras, see the Converters for Keras section below. These wrappers handle the aggregation of model updates as well as any metrics defined for the model automatically. However, it may still be useful to understand how aggregation is handled for a general tff.learning.models.VariableModel .

There are always at least two layers of aggregation in federated learning: local on-device aggregation, and cross-device (or federated) aggregation:

  • Local aggregation . This level of aggregation refers to aggregation across multiple batches of examples owned by an individual client. It applies to both the model parameters (variables), which continue to sequentially evolve as the model is locally trained, as well as the statistics you compute (such as average loss, accuracy, and other metrics), which your model will again update locally as it iterates over each individual client's local data stream.

    Performing aggregation at this level is the responsibility of your model code, and is accomplished using standard TensorFlow constructs.

    The general structure of processing is as follows:

    • The model first constructs tf.Variable s to hold aggregates, such as the number of batches or the number of examples processed, the sum of per-batch or per-example losses, etc.

    • TFF invokes the forward_pass method on your Model multiple times, sequentially over subsequent batches of client data, which allows you to update the variables holding various aggregates as a side effect.

    • Finally, TFF invokes the report_local_unfinalized_metrics method on your Model to allow your model to compile all the summary statistics it collected into a compact set of metrics to be exported by the client. This is where your model code may, for example, divide the sum of losses by the number of examples processed to export the average loss, etc.

  • Federated aggregation . This level of aggregation refers to aggregation across multiple clients (devices) in the system. Again, it applies to both the model parameters (variables), which are being averaged across clients, as well as the metrics your model exported as a result of local aggregation.

    Performing aggregation at this level is the responsibility of TFF. As a model creator, however, you can control this process (more on this below).

    The general structure of processing is as follows:

    • The initial model, and any parameters required for training, are distributed by a server to a subset of clients that will participate in a round of training or evaluation.

    • On each client, independently and in parallel, your model code is invoked repeatedly on a stream of local data batches to produce a new set of model parameters (when training), and a new set of local metrics, as described above (this is local aggregation).

    • TFF runs a distributed aggregation protocol to accumulate and aggregate the model parameters and locally exported metrics across the system. This logic is expressed in a declarative manner using TFF's own federated computation language (not in TensorFlow). See the custom algorithms tutorial for more on the aggregation API.

Abstract interfaces

This basic constructor + metadata interface is represented by the interface tff.learning.models.VariableModel , as follows:

  • The constructor, forward_pass , and report_local_unfinalized_metrics methods should construct model variables, forward pass, and statistics you wish to report, correspondingly. The TensorFlow constructed by those methods must be serializable, as discussed above.

  • The input_spec property, as well as the 3 properties that return subsets of your trainable, non-trainable, and local variables represent the metadata. TFF uses this information to determine how to connect parts of your model to the federated optimization algorithms, and to define internal type signatures to assist in verifying the correctness of the constructed system (so that your model cannot be instantiated over data that does not match what the model is designed to consume).

In addition, the abstract interface tff.learning.models.VariableModel exposes a property metric_finalizers that takes in a metric's unfinalized values (returned by report_local_unfinalized_metrics() ) and returns the finalized metric values. The metric_finalizers and report_local_unfinalized_metrics() method will be used together to build a cross-client metrics aggregator when defining the federated training processes or evaluation computations. For example, a simple tff.learning.metrics.sum_then_finalize aggregator will first sum the unfinalized metric values from clients, and then call the finalizer functions at the server.

You can find examples of how to define your own custom tff.learning.models.VariableModel in the second part of our image classification tutorial, as well as in the example models we use for testing in model_examples.py .

Converters for Keras

Nearly all the information that's required by TFF can be derived by calling tf.keras interfaces, so if you have a Keras model, you can rely on tff.learning.models.from_keras_model to construct a tff.learning.models.VariableModel .

Note that TFF still wants you to provide a constructor - a no-argument model function such as the following:

def model_fn():
  keras_model = ...
  return tff.learning.models.from_keras_model(keras_model, sample_batch, loss=...)

In addition to the model itself, you supply a sample batch of data which TFF uses to determine the type and shape of your model's input. This ensures that TFF can properly instantiate the model for the data that will actually be present on client devices (since we assume this data is not generally available at the time you are constructing the TensorFlow to be serialized).

The use of Keras wrappers is illustrated in our image classification and text generation tutorials.

Federated Computation Builders

The tff.learning package provides several builders for tff.Computation s that perform learning-related tasks; we expect the set of such computations to expand in the future.

Architectural assumptions

Execution

There are two distinct phases in running a federated computation.

  • Compile : TFF first compiles federated learning algorithms into an abstract serialized representation of the entire distributed computation. This is when TensorFlow serialization happens, but other transformations can occur to support more efficient execution. We refer to the serialized representation emitted by the compiler as a federated computation .

  • Execute TFF provides ways to execute these computations. For now, execution is only supported via a local simulation (eg, in a notebook using simulated decentralized data).

A federated computation generated by TFF's Federated Learning API, such as a training algorithm that uses federated model averaging , or a federated evaluation, includes a number of elements, most notably:

  • A serialized form of your model code as well as additional TensorFlow code constructed by the Federated Learning framework to drive your model's training/evaluation loop (such as constructing optimizers, applying model updates, iterating over tf.data.Dataset s, and computing metrics, and applying the aggregated update on the server, to name a few).

  • A declarative specification of the communication between the clients and a server (typically various forms of aggregation across the client devices, and broadcasting from the server to all clients), and how this distributed communication is interleaved with the client-local or server-local execution of TensorFlow code.

The federated computations represented in this serialized form are expressed in a platform-independent internal language distinct from Python, but to use the Federated Learning API, you won't need to concern yourself with the details of this representation. The computations are represented in your Python code as objects of type tff.Computation , which for the most part you can treat as opaque Python callable s.

In the tutorials, you will invoke those federated computations as if they were regular Python functions, to be executed locally. However, TFF is designed to express federated computations in a manner agnostic to most aspects of the execution environment, so that they can potentially be deployable to, eg, groups of devices running Android , or to clusters in a datacenter. Again, the main consequence of this are strong assumptions about serialization . In particular, when you invoke one of the build_... methods described below the computation is fully serialized.

Modeling state

TFF is a functional programming environment, yet many processes of interest in federated learning are stateful. For example, a training loop that involves multiple rounds of federated model averaging is an example of what we could classify as a stateful process . In this process, the state that evolves from round to round includes the set of model parameters that are being trained, and possibly additional state associated with the optimizer (eg, a momentum vector).

Since TFF is functional, stateful processes are modeled in TFF as computations that accept the current state as an input and then provide the updated state as an output. In order to fully define a stateful process, one also needs to specify where the initial state comes from (otherwise we cannot bootstrap the process). This is captured in the definition of the helper class tff.templates.IterativeProcess , with the 2 properties initialize and next corresponding to the initialization and iteration, respectively.

Available builders

At the moment, TFF provides various builder functions that generate federated computations for federated training and evaluation. Two notable examples include:

Datasets

Architectural assumptions

Client selection

In the typical federated learning scenario, we have a large population of potentially hundreds of millions of client devices, of which only a small portion may be active and available for training at any given moment (for example, this may be limited to clients that are plugged in to a power source, not on a metered network, and otherwise idle). Generally, the set of clients available to participate in training or evaluation is outside of the developer's control. Furthermore, as it's impractical to coordinate millions of clients, a typical round of training or evaluation will include only a fraction of the available clients, which may be sampled at random .

The key consequence of this is that federated computations, by design, are expressed in a manner that is oblivious to the exact set of participants; all processing is expressed as aggregate operations on an abstract group of anonymous clients , and that group might vary from one round of training to another. The actual binding of the computation to the concrete participants, and thus to the concrete data they feed into the computation, is thus modeled outside of the computation itself.

In order to simulate a realistic deployment of your federated learning code, you will generally write a training loop that looks like this:

trainer = tff.learning.algorithms.build_weighted_fed_avg(...)
state = trainer.initialize()
federated_training_data = ...

def sample(federate_data):
  return ...

while True:
  data_for_this_round = sample(federated_training_data)
  result = trainer.next(state, data_for_this_round)
  state = result.state

In order to facilitate this, when using TFF in simulations, federated data is accepted as Python list s, with one element per participating client device to represent that device's local tf.data.Dataset .

Abstract interfaces

In order to standardize dealing with simulated federated data sets, TFF provides an abstract interface tff.simulation.datasets.ClientData , which allows one to enumerate the set of clients, and to construct a tf.data.Dataset that contains the data of a particular client. Those tf.data.Dataset s can be fed directly as input to the generated federated computations in eager mode.

It should be noted that the ability to access client identities is a feature that's only provided by the datasets for use in simulations, where the ability to train on data from specific subsets of clients may be needed (eg, to simulate the diurnal availability of different types of clients). The compiled computations and the underlying runtime do not involve any notion of client identity. Once data from a specific subset of clients has been selected as an input, eg, in a call to tff.templates.IterativeProcess.next , client identities no longer appear in it.

Available data sets

We have dedicated the namespace tff.simulation.datasets for datasets that implement the tff.simulation.datasets.ClientData interface for use in simulations, and seeded it with datasets to support the image classification and text generation tutorials. We'd like to encourage you to contribute your own datasets to the platform.

,

Overview

This document introduces interfaces that facilitate federated learning tasks, such as federated training or evaluation with existing machine learning models implemented in TensorFlow. In designing these interfaces, our primary goal was to make it possible to experiment with federated learning without requiring the knowledge of how it works under the hood, and to evaluate the implemented federated learning algorithms on a variety of existing models and data. We encourage you to contribute back to the platform. TFF has been designed with extensibility and composability in mind, and we welcome contributions; we are excited to see what you come up with!

The interfaces offered by this layer consist of the following three key parts:

  • Models . Classes and helper functions that allow you to wrap your existing models for use with TFF. Wrapping a model can be as simple as calling a single wrapping function (eg, tff.learning.models.from_keras_model ), or defining a subclass of the tff.learning.models.VariableModel interface for full customizability.

  • Federated Computation Builders . Helper functions that construct federated computations for training or evaluation, using your existing models.

  • Datasets . Canned collections of data that you can download and access in Python for use in simulating federated learning scenarios. Although federated learning is designed for use with decentralized data that cannot be simply downloaded at a centralized location, at the research and development stages it is often convenient to conduct initial experiments using data that can be downloaded and manipulated locally, especially for developers who might be new to the approach.

These interfaces are defined primarily in the tff.learning namespace, except for research data sets and other simulation-related capabilities that have been grouped in tff.simulation . This layer is implemented using lower-level interfaces offered by the Federated Core (FC) , which also provides a runtime environment.

Before proceeding, we recommend that you first review the tutorials on image classification and text generation , as they introduce most of the concepts described here using concrete examples. If you're interested in learning more about how TFF works, you may want to skim over the custom algorithms tutorial as an introduction to the lower-level interfaces we use to express the logic of federated computations, and to study the existing implementation of the tff.learning interfaces.

Models

Architectural assumptions

Serialization

TFF aims at supporting a variety of distributed learning scenarios in which the machine learning model code you write might be executing on a large number of heterogeneous clients with diverse capabilities. While at one end of the spectrum, in some applications those clients might be powerful database servers, many important uses our platform intends to support involve mobile and embedded devices with limited resources. We cannot assume that these devices are capable of hosting Python runtimes; the only thing we can assume at this point is that they are capable of hosting a local TensorFlow runtime. Thus, a fundamental architectural assumption we make in TFF is that your model code must be serializable as a TensorFlow graph.

You can (and should) still develop your TF code following the latest best practices like using eager mode. However, the final code must be serializable (eg, can be wrapped as a tf.function for eager-mode code). This ensures that any Python state or control flow necessary at execution time can be serialized (possibly with the help of Autograph ).

Currently, TensorFlow does not fully support serializing and deserializing eager-mode TensorFlow. Thus, serialization in TFF currently follows the TF 1.0 pattern, where all code must be constructed inside a tf.Graph that TFF controls. This means currently TFF cannot consume an already-constructed model; instead, the model definition logic is packaged in a no-arg function that returns a tff.learning.models.VariableModel . This function is then called by TFF to ensure all components of the model are serialized. In addition, being a strongly-typed environment, TFF will require a little bit of additional metadata , such as a specification of your model's input type.

Aggregation

We strongly recommend most users construct models using Keras, see the Converters for Keras section below. These wrappers handle the aggregation of model updates as well as any metrics defined for the model automatically. However, it may still be useful to understand how aggregation is handled for a general tff.learning.models.VariableModel .

There are always at least two layers of aggregation in federated learning: local on-device aggregation, and cross-device (or federated) aggregation:

  • Local aggregation . This level of aggregation refers to aggregation across multiple batches of examples owned by an individual client. It applies to both the model parameters (variables), which continue to sequentially evolve as the model is locally trained, as well as the statistics you compute (such as average loss, accuracy, and other metrics), which your model will again update locally as it iterates over each individual client's local data stream.

    Performing aggregation at this level is the responsibility of your model code, and is accomplished using standard TensorFlow constructs.

    The general structure of processing is as follows:

    • The model first constructs tf.Variable s to hold aggregates, such as the number of batches or the number of examples processed, the sum of per-batch or per-example losses, etc.

    • TFF invokes the forward_pass method on your Model multiple times, sequentially over subsequent batches of client data, which allows you to update the variables holding various aggregates as a side effect.

    • Finally, TFF invokes the report_local_unfinalized_metrics method on your Model to allow your model to compile all the summary statistics it collected into a compact set of metrics to be exported by the client. This is where your model code may, for example, divide the sum of losses by the number of examples processed to export the average loss, etc.

  • Federated aggregation . This level of aggregation refers to aggregation across multiple clients (devices) in the system. Again, it applies to both the model parameters (variables), which are being averaged across clients, as well as the metrics your model exported as a result of local aggregation.

    Performing aggregation at this level is the responsibility of TFF. As a model creator, however, you can control this process (more on this below).

    The general structure of processing is as follows:

    • The initial model, and any parameters required for training, are distributed by a server to a subset of clients that will participate in a round of training or evaluation.

    • On each client, independently and in parallel, your model code is invoked repeatedly on a stream of local data batches to produce a new set of model parameters (when training), and a new set of local metrics, as described above (this is local aggregation).

    • TFF runs a distributed aggregation protocol to accumulate and aggregate the model parameters and locally exported metrics across the system. This logic is expressed in a declarative manner using TFF's own federated computation language (not in TensorFlow). See the custom algorithms tutorial for more on the aggregation API.

Abstract interfaces

This basic constructor + metadata interface is represented by the interface tff.learning.models.VariableModel , as follows:

  • The constructor, forward_pass , and report_local_unfinalized_metrics methods should construct model variables, forward pass, and statistics you wish to report, correspondingly. The TensorFlow constructed by those methods must be serializable, as discussed above.

  • The input_spec property, as well as the 3 properties that return subsets of your trainable, non-trainable, and local variables represent the metadata. TFF uses this information to determine how to connect parts of your model to the federated optimization algorithms, and to define internal type signatures to assist in verifying the correctness of the constructed system (so that your model cannot be instantiated over data that does not match what the model is designed to consume).

In addition, the abstract interface tff.learning.models.VariableModel exposes a property metric_finalizers that takes in a metric's unfinalized values (returned by report_local_unfinalized_metrics() ) and returns the finalized metric values. The metric_finalizers and report_local_unfinalized_metrics() method will be used together to build a cross-client metrics aggregator when defining the federated training processes or evaluation computations. For example, a simple tff.learning.metrics.sum_then_finalize aggregator will first sum the unfinalized metric values from clients, and then call the finalizer functions at the server.

You can find examples of how to define your own custom tff.learning.models.VariableModel in the second part of our image classification tutorial, as well as in the example models we use for testing in model_examples.py .

Converters for Keras

Nearly all the information that's required by TFF can be derived by calling tf.keras interfaces, so if you have a Keras model, you can rely on tff.learning.models.from_keras_model to construct a tff.learning.models.VariableModel .

Note that TFF still wants you to provide a constructor - a no-argument model function such as the following:

def model_fn():
  keras_model = ...
  return tff.learning.models.from_keras_model(keras_model, sample_batch, loss=...)

In addition to the model itself, you supply a sample batch of data which TFF uses to determine the type and shape of your model's input. This ensures that TFF can properly instantiate the model for the data that will actually be present on client devices (since we assume this data is not generally available at the time you are constructing the TensorFlow to be serialized).

The use of Keras wrappers is illustrated in our image classification and text generation tutorials.

Federated Computation Builders

The tff.learning package provides several builders for tff.Computation s that perform learning-related tasks; we expect the set of such computations to expand in the future.

Architectural assumptions

Execution

There are two distinct phases in running a federated computation.

  • Compile : TFF first compiles federated learning algorithms into an abstract serialized representation of the entire distributed computation. This is when TensorFlow serialization happens, but other transformations can occur to support more efficient execution. We refer to the serialized representation emitted by the compiler as a federated computation .

  • Execute TFF provides ways to execute these computations. For now, execution is only supported via a local simulation (eg, in a notebook using simulated decentralized data).

A federated computation generated by TFF's Federated Learning API, such as a training algorithm that uses federated model averaging , or a federated evaluation, includes a number of elements, most notably:

  • A serialized form of your model code as well as additional TensorFlow code constructed by the Federated Learning framework to drive your model's training/evaluation loop (such as constructing optimizers, applying model updates, iterating over tf.data.Dataset s, and computing metrics, and applying the aggregated update on the server, to name a few).

  • A declarative specification of the communication between the clients and a server (typically various forms of aggregation across the client devices, and broadcasting from the server to all clients), and how this distributed communication is interleaved with the client-local or server-local execution of TensorFlow code.

The federated computations represented in this serialized form are expressed in a platform-independent internal language distinct from Python, but to use the Federated Learning API, you won't need to concern yourself with the details of this representation. The computations are represented in your Python code as objects of type tff.Computation , which for the most part you can treat as opaque Python callable s.

In the tutorials, you will invoke those federated computations as if they were regular Python functions, to be executed locally. However, TFF is designed to express federated computations in a manner agnostic to most aspects of the execution environment, so that they can potentially be deployable to, eg, groups of devices running Android , or to clusters in a datacenter. Again, the main consequence of this are strong assumptions about serialization . In particular, when you invoke one of the build_... methods described below the computation is fully serialized.

Modeling state

TFF is a functional programming environment, yet many processes of interest in federated learning are stateful. For example, a training loop that involves multiple rounds of federated model averaging is an example of what we could classify as a stateful process . In this process, the state that evolves from round to round includes the set of model parameters that are being trained, and possibly additional state associated with the optimizer (eg, a momentum vector).

Since TFF is functional, stateful processes are modeled in TFF as computations that accept the current state as an input and then provide the updated state as an output. In order to fully define a stateful process, one also needs to specify where the initial state comes from (otherwise we cannot bootstrap the process). This is captured in the definition of the helper class tff.templates.IterativeProcess , with the 2 properties initialize and next corresponding to the initialization and iteration, respectively.

Available builders

At the moment, TFF provides various builder functions that generate federated computations for federated training and evaluation. Two notable examples include:

Datasets

Architectural assumptions

Client selection

In the typical federated learning scenario, we have a large population of potentially hundreds of millions of client devices, of which only a small portion may be active and available for training at any given moment (for example, this may be limited to clients that are plugged in to a power source, not on a metered network, and otherwise idle). Generally, the set of clients available to participate in training or evaluation is outside of the developer's control. Furthermore, as it's impractical to coordinate millions of clients, a typical round of training or evaluation will include only a fraction of the available clients, which may be sampled at random .

The key consequence of this is that federated computations, by design, are expressed in a manner that is oblivious to the exact set of participants; all processing is expressed as aggregate operations on an abstract group of anonymous clients , and that group might vary from one round of training to another. The actual binding of the computation to the concrete participants, and thus to the concrete data they feed into the computation, is thus modeled outside of the computation itself.

In order to simulate a realistic deployment of your federated learning code, you will generally write a training loop that looks like this:

trainer = tff.learning.algorithms.build_weighted_fed_avg(...)
state = trainer.initialize()
federated_training_data = ...

def sample(federate_data):
  return ...

while True:
  data_for_this_round = sample(federated_training_data)
  result = trainer.next(state, data_for_this_round)
  state = result.state

In order to facilitate this, when using TFF in simulations, federated data is accepted as Python list s, with one element per participating client device to represent that device's local tf.data.Dataset .

Abstract interfaces

In order to standardize dealing with simulated federated data sets, TFF provides an abstract interface tff.simulation.datasets.ClientData , which allows one to enumerate the set of clients, and to construct a tf.data.Dataset that contains the data of a particular client. Those tf.data.Dataset s can be fed directly as input to the generated federated computations in eager mode.

It should be noted that the ability to access client identities is a feature that's only provided by the datasets for use in simulations, where the ability to train on data from specific subsets of clients may be needed (eg, to simulate the diurnal availability of different types of clients). The compiled computations and the underlying runtime do not involve any notion of client identity. Once data from a specific subset of clients has been selected as an input, eg, in a call to tff.templates.IterativeProcess.next , client identities no longer appear in it.

Available data sets

We have dedicated the namespace tff.simulation.datasets for datasets that implement the tff.simulation.datasets.ClientData interface for use in simulations, and seeded it with datasets to support the image classification and text generation tutorials. We'd like to encourage you to contribute your own datasets to the platform.