learn2learn

learnablesMIT更新放缓

基于 PyTorch 的元学习研究库,提供 MAML、Meta-SGD 等算法实现和统一接口,方便快速复现和开发少样本学习、元强化学习实验。

A PyTorch Library for Meta-learning Research

v0.2.1发布于 2023-06-27 18:04 UTC2,894star356fork同步于 2026-11-07 07:29 UTC

怎么上手

由 README 提炼,执行前请确认
pip install learn2learn
硬件要求按 README 说明

README 未说明

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

基于 PyTorch 的元学习研究库,帮你快速搭原型并公平复现实验

基于 PyTorch 的元学习研究库,提供 MAML、Meta-SGD 等算法实现和统一接口,方便快速复现和开发少样本学习、元强化学习实验。

核心能力

  • 用 Taskset 和 transforms 从任意数据集构造 few-shot 任务
  • 提供 MAML、ProtoNets、ANIL 等算法的 GBML 高层封装
  • 用 LearnableOptimizer 和 ParameterUpdate 做可微优化与元下降
  • 内置 Omniglot、mini/tiered-ImageNet 等标准 few-shot 数据集
  • 用 AsyncVectorEnv 多线程并行元强化学习环境

容易踩的坑

README 未说明是否需要额外下载数据集;元强化学习部分依赖 cherry 等 PyTorch 生态库,需自行确认版本兼容

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v0.2.1
  1. v0.2.1MetaModules, TasksetSampler, Adapters & LoRA, more examples and tutorials + removed dependency.最新正式版2023-06-27 · 2023-06-27 18:04 UTC

    Like 0.2.0 but with qpth made optional.

  2. v0.2.0MetaModules, TasksetSampler, Adapters & LoRA, more examples and tutorials2023-06-03 · 2023-06-03 21:18 UTC
    查看更新说明

    Added

    • New vision example: MAML++. (@Theo Morales)
    • Add tutorial: "Demystifying Task Transforms", (Varad Pimpalkhute)
    • Add l2l.nn.MetaModule and l2l.nn.ParameterTransform for parameter-efficient finetuning.
    • Add l2l.nn.freezeand l2l.nn.unfreeze.
    • Add Adapters and LoRA examples.
    • Add TasksetSampler, compatible with PyTorch's Dataloaders.

    Changed

    • Documentation: uses mkdocstrings instead of pydoc-markdown.
    • Remove text/news_topic_classification.py example.
    • Rename TaskDataset to Taskset.

    Fixed

    • MAML Toy example. (@Theo Morales)
    • Example for detach_module. (Nimish Sanghi)
    • Loading duplicate FGVC Aircraft images.
    • Move vision datasets to Zenodo. (mini-ImageNet, tiered-ImageNet, FC100, CIFAR-FS, CUB200)
    • mini-ImageNet targets are now ints (not np.float64).
    • Swap family for variants in FGVCAircraft, as in MetaDataset.
  3. v0.1.7Aircraft, CUB200 bounding boxes, pretrained_backbones, RandomClassRotation, fixed memory_leak.2022-02-10 · 2022-02-10 03:30 UTC
    查看更新说明

    v0.1.7

    Added

    • Bounding box cropping for Aircraft and CUB200.
    • Pretrained weights for vision models with: l2l.vision.models.get_pretrained_backbone().
    • Add keep_requires_grad flag to detach_module. (Zhaofeng Wu)

    Fixed

  4. v0.1.6Add Lightning interface, Backbone classes, new classifiers, and data utils.2021-09-07 · 2021-09-07 06:56 UTC
    查看更新说明

    v0.1.6

    Added

    • PyTorch Lightning interface to MAML, ANIL, ProtoNet, MetaOptNet.
    • Automatic batcher for Lightning: l2l.data.EpisodicBatcher.
    • l2l.nn.PrototypicalClassifier and l2l.nn.SVMClassifier.
    • Add l2l.vision.models.WRN28.
    • Separate modules for CNN4Backbone, ResNet12Backbone, WRN28Backbones w/ pretrained weights.
    • Add l2l.data.OnDeviceDataset and implement device parameter for benchmarks.
    • (Beta) Add l2l.data.partition_task and l2l.data.InfiniteIterator.

    Changed

    • Renamed and clarify dropout parameters for ResNet12.

    Fixed

    • Improved support for 1D inputs in l2l.nn.KroneckerLinear. (@timweiland)
  5. v0.1.5Fix windows installation.2020-12-05 · 2020-12-05 18:02 UTC
    查看更新说明

    v0.1.5

    Fixed

    • Fix setup.py for windows installs.

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    Test Status arXiv

    learn2learn is a software library for meta-learning research.

    learn2learn builds on top of PyTorch to accelerate two aspects of the meta-learning research cycle:

    • fast prototyping, essential in letting researchers quickly try new ideas, and
    • correct reproducibility, ensuring that these ideas are evaluated fairly.

    learn2learn provides low-level utilities and unified interface to create new algorithms and domains, together with high-quality implementations of existing algorithms and standardized benchmarks. It retains compatibility with torchvision, torchaudio, torchtext, cherry, and any other PyTorch-based library you might be using.

    To learn more, see our whitepaper: arXiv:2008.12284

    Overview

    • learn2learn.data: Taskset and transforms to create few-shot tasks from any PyTorch dataset.
    • learn2learn.vision: Models, datasets, and benchmarks for computer vision and few-shot learning.
    • learn2learn.gym: Environment and utilities for meta-reinforcement learning.
    • learn2learn.algorithms: High-level wrappers for existing meta-learning algorithms.
    • learn2learn.optim: Utilities and algorithms for differentiable optimization and meta-descent.

    Resources

    Installation

    pip install learn2learn
    

    Snippets & Examples

    The following snippets provide a sneak peek at the functionalities of learn2learn.

    High-level Wrappers

    For more algorithms (ProtoNets, ANIL, Meta-SGD, Reptile, Meta-Curvature, KFO) refer to the examples folder. Most of them can be implemented with with the GBML wrapper. (documentation).

    maml = l2l.algorithms.MAML(model, lr=0.1)
    opt = torch.optim.SGD(maml.parameters(), lr=0.001)
    for iteration in range(10):
        opt.zero_grad()
        task_model = maml.clone()  # torch.clone() for nn.Modules
        adaptation_loss = compute_loss(task_model)
        task_model.adapt(adaptation_loss)  # computes gradient, update task_model in-place
        evaluation_loss = compute_loss(task_model)
        evaluation_loss.backward()  # gradients w.r.t. maml.parameters()
        opt.step()
    

    Learn any kind of optimization algorithm with the LearnableOptimizer. (example and documentation)

    linear = nn.Linear(784, 10)
    transform = l2l.optim.ModuleTransform(l2l.nn.Scale)
    metaopt = l2l.optim.LearnableOptimizer(linear, transform, lr=0.01)  # metaopt has .step()
    opt = torch.optim.SGD(metaopt.parameters(), lr=0.001)  # metaopt also has .parameters()
    
    metaopt.zero_grad()
    opt.zero_grad()
    error = loss(linear(X), y)
    error.backward()
    opt.step()  # update metaopt
    metaopt.step()  # update linear
    

    Learning Domains

    Many standardized datasets (Omniglot, mini-/tiered-ImageNet, FC100, CIFAR-FS) are readily available in learn2learn.vision.datasets. (documentation)

    dataset = l2l.data.MetaDataset(MyDataset())  # any PyTorch dataset
    transforms = [  # Easy to define your own transform
        l2l.data.transforms.NWays(dataset, n=5),
        l2l.data.transforms.KShots(dataset, k=1),
        l2l.data.transforms.LoadData(dataset),
    ]
    taskset = Taskset(dataset, transforms, num_tasks=20000)
    for task in taskset:
        X, y = task
        # Meta-train on the task
    

    Parallelize your own meta-environments with AsyncVectorEnv, or use the standardized ones. (documentation)

    def make_env():
        env = l2l.gym.HalfCheetahForwardBackwardEnv()
        env = cherry.envs.ActionSpaceScaler(env)
        return env
    
    env = l2l.gym.AsyncVectorEnv([make_env for _ in range(16)])  # uses 16 threads
    for task_config in env.sample_tasks(20):
        env.set_task(task)  # all threads receive the same task
        state = env.reset()  # use standard Gym API
        action = my_policy(env)
        env.step(action)
    

    Low-Level Utilities

    Learn and differentiate through updates of PyTorch Modules. (documentation)

    
    model = MyModel()
    transform = l2l.optim.KroneckerTransform(l2l.nn.KroneckerLinear)
    learned_update = l2l.optim.ParameterUpdate(  # learnable update function
            model.parameters(), transform)
    clone = l2l.clone_module(model)  # torch.clone() for nn.Modules
    error = loss(clone(X), y)
    updates = learned_update(  # similar API as torch.autograd.grad
        error,
        clone.parameters(),
        create_graph=True,
    )
    l2l.update_module(clone, updates=updates)
    loss(clone(X), y).backward()  # Gradients w.r.t model.parameters() and learned_update.parameters()
    

    Changelog

    A human-readable changelog is available in the CHANGELOG.md file.

    Citation

    To cite the learn2learn repository in your academic publications, please use the following reference.

    Arnold, Sebastien M. R., Praateek Mahajan, Debajyoti Datta, Ian Bunner, and Konstantinos Saitas Zarkias. 2020. “learn2learn: A Library for Meta-Learning Research.” arXiv [cs.LG]. http://arxiv.org/abs/2008.12284.

    You can also use the following Bibtex entry.

    @article{Arnold2020-ss,
      title         = "learn2learn: A Library for {Meta-Learning} Research",
      author        = "Arnold, S{\'e}bastien M R and Mahajan, Praateek and Datta,
                       Debajyoti and Bunner, Ian and Zarkias, Konstantinos Saitas",
      month         =  aug,
      year          =  2020,
      url           = "http://arxiv.org/abs/2008.12284",
      archivePrefix = "arXiv",
      primaryClass  = "cs.LG",
      eprint        = "2008.12284"
    }
    
    

    Acknowledgements & Friends

    1. TorchMeta is similar library, with a focus on datasets for supervised meta-learning.
    2. higher is a PyTorch library that enables differentiating through optimization inner-loops. While they monkey-patch nn.Module to be stateless, learn2learn retains the stateful PyTorch look-and-feel. For more information, refer to their ArXiv paper.
    3. We are thankful to the following open-source implementations which helped guide the design of learn2learn: