Inference problem AttributeError: '_FakeLoader' object has no attribute 'noops'

Hello I am trying to do inference on a FastApi sever with this code:

async def setup_learner():
    # await gdl(drive_file_id, path / export_file_name)
    #path/export_file_name is on my pysical machine via manual download
    try:
        learn = torch.load(path/export_file_name, map_location=torch.device('cpu'))
        learn.dls.device = 'cpu'
        return learn
    except RuntimeError as e:
        if len(e.args) > 0 and 'CPU-only machine' in e.args[0]:
            print(e)
            message = "\n\nThis model was trained with an old version of fastai and will not work in a CPU environment.\n\nPlease update the fastai library in your training environment and export your model again.\n\nSee instructions for 'Returning to work' at https://course.fast.ai."
            raise RuntimeError(message)
        else:
            raise

learn = None
@app.on_event("startup")
async def startup_event():
    global learn
    loop = asyncio.get_event_loop()#get event loop
    tasks = [asyncio.ensure_future(setup_learner())] #assign some task
    learn = (await asyncio.gather(*tasks))[0] #get tasks

@app.route('/analyze', methods=['POST'])
async def analyze(request):
    img_data = await request.form()
    in_memory_file = await (img_data['file'].read())

    #predict
    prediction, loc, prob_classes = learn.predict(in_memory_file)
    print(prediction, loc, prob_classes)

    return JSONResponse({'msg':'msg'})

And I recieve these two errors

Traceback (most recent call last):-----| 0.00% [0/1 00:00<00:00]
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.7/multiprocessing/spawn.py", line 105, in spawn_main
    exitcode = _main(fd)
  File "/usr/lib/python3.7/multiprocessing/spawn.py", line 115, in _main
    self = reduction.pickle.load(from_parent)
AttributeError: '_FakeLoader' object has no attribute 'noops'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.7/multiprocessing/spawn.py", line 105, in spawn_main
    exitcode = _main(fd)
  File "/usr/lib/python3.7/multiprocessing/spawn.py", line 115, in _main
    self = reduction.pickle.load(from_parent)
AttributeError: '_FakeLoader' object has no attribute 'noops'
INFO:     127.0.0.1:59896 - "POST /analyze HTTP/1.1" 500 Internal Server Error
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/home/nole/.local/lib/python3.7/site-packages/uvicorn/protocols/http/httptools_impl.py", line 385, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/home/nole/.local/lib/python3.7/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/home/nole/.local/lib/python3.7/site-packages/fastapi/applications.py", line 149, in __call__
    await super().__call__(scope, receive, send)
  File "/home/nole/.local/lib/python3.7/site-packages/starlette/applications.py", line 102, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/home/nole/.local/lib/python3.7/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/home/nole/.local/lib/python3.7/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/home/nole/.local/lib/python3.7/site-packages/starlette/middleware/cors.py", line 84, in __call__
    await self.simple_response(scope, receive, send, request_headers=headers)
  File "/home/nole/.local/lib/python3.7/site-packages/starlette/middleware/cors.py", line 140, in simple_response
    await self.app(scope, receive, send)
  File "/home/nole/.local/lib/python3.7/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/home/nole/.local/lib/python3.7/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/home/nole/.local/lib/python3.7/site-packages/starlette/routing.py", line 550, in __call__
    await route.handle(scope, receive, send)
  File "/home/nole/.local/lib/python3.7/site-packages/starlette/routing.py", line 227, in handle
    await self.app(scope, receive, send)
  File "/home/nole/.local/lib/python3.7/site-packages/starlette/routing.py", line 41, in app
    response = await func(request)
  File "./main.py", line 194, in analyze
    prediction, loc, prob_classes = learn.predict(in_memory_file)
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 231, in predict
    inp,preds,_,dec_preds = self.get_preds(dl=dl, with_input=True, with_decoded=True)
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 219, in get_preds
    self._do_epoch_validate(dl=dl)
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 178, in _do_epoch_validate
    dl,*_ = change_attrs(dl, names, old, has);       self('after_validate')
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 124, in __call__
    def __call__(self, event_name): L(event_name).map(self._call_one)
  File "/home/nole/.local/lib/python3.7/site-packages/fastcore/foundation.py", line 372, in map
    return self._new(map(g, self))
  File "/home/nole/.local/lib/python3.7/site-packages/fastcore/foundation.py", line 323, in _new
    def _new(self, items, *args, **kwargs): return type(self)(items, *args, use_list=None, **kwargs)
  File "/home/nole/.local/lib/python3.7/site-packages/fastcore/foundation.py", line 41, in __call__
    res = super().__call__(*((x,) + args), **kwargs)
  File "/home/nole/.local/lib/python3.7/site-packages/fastcore/foundation.py", line 314, in __init__
    items = list(items) if use_list else _listify(items)
  File "/home/nole/.local/lib/python3.7/site-packages/fastcore/foundation.py", line 250, in _listify
    if is_iter(o): return list(o)
  File "/home/nole/.local/lib/python3.7/site-packages/fastcore/foundation.py", line 216, in __call__
    return self.fn(*fargs, **kwargs)
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 127, in _call_one
    [cb(event_name) for cb in sort_by_run(self.cbs)]
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 127, in <listcomp>
    [cb(event_name) for cb in sort_by_run(self.cbs)]
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/callback/core.py", line 24, in __call__
    if self.run and _run: getattr(self, event_name, noop)()
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/callback/core.py", line 95, in after_validate
    if self.with_input:     self.inputs  = detuplify(to_concat(self.inputs, dim=self.concat_dim))
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/torch_core.py", line 213, in to_concat
    if is_listy(xs[0]): return type(xs[0])([to_concat([x[i] for x in xs], dim=dim) for i in range_of(xs[0])])
IndexError: list index out of range

I’m pretty sure that the learner is all setup as I’ve done print calls to make sure the learner instance is available before predict. I trained the model on colab, without doing .to_fp16 and it worked in that environment. My machine info is as follows:

ubuntu                      
    description: Computer
    width: 64 bits
    capabilities: smp vsyscall32
  *-core
       description: Motherboard
       physical id: 0
     *-memory
          description: System memory
          physical id: 0
          size: 4GiB
     *-cpu
          product: Intel(R) Pentium(R) Silver N5000 CPU @ 1.10GHz
          vendor: Intel Corp.
          physical id: 1
          bus info: cpu@0
          size: 2526MHz
          capacity: 2700MHz
          width: 64 bits
          capabilities: fpu fpu_exception wp vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp x86-64 constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg cx16 xtpr pdcm sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave rdrand lahf_lm 3dnowprefetch cpuid_fault cat_l2 pti cdp_l2 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust smep erms mpx rdt_a rdseed smap clflushopt intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts umip rdpid md_clear arch_capabilities cpufreq

You’re 100% sure your fastai2 and fastcore versions line up? If so, what versions are you using?

I believe so.

fastai2                  0.0.16               
fastcore                 0.1.16 

I checked via pip3 list

the class for the image I am trying to classify is <class bytes> should I convert it to another format?

@muellerzr
Thanks for your help. As an update I decided to see if it was simply my machine so I used this code with no error on a simple test.py script:

from fastai2.vision.all import *

path = Path()
path.ls(file_exts='.pkl')

learn_inf = load_learner(path/'export.pkl')
vocab = learn_inf.dls.vocab.o2i.keys()
print(vocab)

img= Path("./index.jpeg")
prediction, loc, prob_classes = learn_inf.predict(img)
print(prediction, loc, prob_classes)

Which properly prints out

I-210+n tensor(7) tensor([7.9076e-08, 4.3723e-05, 9.5849e-06, 9.9134e-04, 7.5235e-08, 4.8674e-04,
        1.0136e-02, 6.0512e-01, 3.8291e-01, 8.4351e-05, 2.2064e-04])

And for the sake of comparison I used this code with FastApi in another directory which was run with uvicorn main:app --reload with the filename being main.py :

from fastapi import FastAPI
from fastai2.vision.all import *
app = FastAPI()

path = Path()
path.ls(file_exts='.pkl')

learn_inf = load_learner(path/'export.pkl')
vocab = learn_inf.dls.vocab.o2i.keys()
print(vocab)

img= Path("./index.jpeg")
prediction, loc, prob_classes = learn_inf.predict(img)
print(prediction, loc, prob_classes)

@app.get("/")
async def root():
    return {"message": "Hello World"}

And unfortunately I still get the same error messages:

Traceback (most recent call last):-----| 0.00% [0/1 00:00<00:00]
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.7/multiprocessing/spawn.py", line 105, in spawn_main
    exitcode = _main(fd)
  File "/usr/lib/python3.7/multiprocessing/spawn.py", line 115, in _main
    self = reduction.pickle.load(from_parent)
AttributeError: '_FakeLoader' object has no attribute 'noops'
  File "/usr/lib/python3.7/multiprocessing/spawn.py", line 105, in spawn_main
    exitcode = _main(fd)
  File "/usr/lib/python3.7/multiprocessing/spawn.py", line 115, in _main
    self = reduction.pickle.load(from_parent)
AttributeError: '_FakeLoader' object has no attribute 'noops'
Process SpawnProcess-2:                                         
Traceback (most recent call last):
  File "/home/nole/.local/lib/python3.7/site-packages/torch/utils/data/dataloader.py", line 761, in _try_get_data
    data = self._data_queue.get(timeout=timeout)
  File "/usr/lib/python3.7/multiprocessing/queues.py", line 104, in get
    if not self._poll(timeout):
  File "/usr/lib/python3.7/multiprocessing/connection.py", line 257, in poll
    return self._poll(timeout)
  File "/usr/lib/python3.7/multiprocessing/connection.py", line 414, in _poll
    r = wait([self], timeout)
  File "/usr/lib/python3.7/multiprocessing/connection.py", line 920, in wait
    ready = selector.select(timeout)
  File "/usr/lib/python3.7/selectors.py", line 415, in select
    fd_event_list = self._selector.poll(timeout)
  File "/home/nole/.local/lib/python3.7/site-packages/torch/utils/data/_utils/signal_handling.py", line 66, in handler
    _error_if_any_worker_fails()
RuntimeError: DataLoader worker (pid 22422) exited unexpectedly with exit code 1. Details are lost due to multiprocessing. Rerunning with num_workers=0 may give better error trace.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 175, in _do_epoch_validate
    with torch.no_grad(): self.all_batches()
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 143, in all_batches
    for o in enumerate(self.dl): self.one_batch(*o)
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/data/load.py", line 97, in __iter__
    for b in _loaders[self.fake_l.num_workers==0](self.fake_l):
  File "/home/nole/.local/lib/python3.7/site-packages/torch/utils/data/dataloader.py", line 345, in __next__
    data = self._next_data()
  File "/home/nole/.local/lib/python3.7/site-packages/torch/utils/data/dataloader.py", line 841, in _next_data
    idx, data = self._get_data()
  File "/home/nole/.local/lib/python3.7/site-packages/torch/utils/data/dataloader.py", line 808, in _get_data
    success, data = self._try_get_data()
  File "/home/nole/.local/lib/python3.7/site-packages/torch/utils/data/dataloader.py", line 774, in _try_get_data
    raise RuntimeError('DataLoader worker (pid(s) {}) exited unexpectedly'.format(pids_str))
RuntimeError: DataLoader worker (pid(s) 22421, 22422) exited unexpectedly

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.7/multiprocessing/process.py", line 297, in _bootstrap
    self.run()
  File "/usr/lib/python3.7/multiprocessing/process.py", line 99, in run
    self._target(*self._args, **self._kwargs)
  File "/home/nole/.local/lib/python3.7/site-packages/uvicorn/subprocess.py", line 61, in subprocess_started
    target(sockets=sockets)
  File "/home/nole/.local/lib/python3.7/site-packages/uvicorn/main.py", line 382, in run
    loop.run_until_complete(self.serve(sockets=sockets))
  File "uvloop/loop.pyx", line 1456, in uvloop.loop.Loop.run_until_complete
  File "/home/nole/.local/lib/python3.7/site-packages/uvicorn/main.py", line 389, in serve
    config.load()
  File "/home/nole/.local/lib/python3.7/site-packages/uvicorn/config.py", line 288, in load
    self.loaded_app = import_from_string(self.app)
  File "/home/nole/.local/lib/python3.7/site-packages/uvicorn/importer.py", line 20, in import_from_string
    module = importlib.import_module(module_str)
  File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "./main.py", line 15, in <module>
    prediction, loc, prob_classes = learn_inf.predict(img)
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 231, in predict
    inp,preds,_,dec_preds = self.get_preds(dl=dl, with_input=True, with_decoded=True)
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 219, in get_preds
    self._do_epoch_validate(dl=dl)
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 178, in _do_epoch_validate
    dl,*_ = change_attrs(dl, names, old, has);       self('after_validate')
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 124, in __call__
    def __call__(self, event_name): L(event_name).map(self._call_one)
  File "/home/nole/.local/lib/python3.7/site-packages/fastcore/foundation.py", line 372, in map
    return self._new(map(g, self))
  File "/home/nole/.local/lib/python3.7/site-packages/fastcore/foundation.py", line 323, in _new
    def _new(self, items, *args, **kwargs): return type(self)(items, *args, use_list=None, **kwargs)
  File "/home/nole/.local/lib/python3.7/site-packages/fastcore/foundation.py", line 41, in __call__
    res = super().__call__(*((x,) + args), **kwargs)
  File "/home/nole/.local/lib/python3.7/site-packages/fastcore/foundation.py", line 314, in __init__
    items = list(items) if use_list else _listify(items)
  File "/home/nole/.local/lib/python3.7/site-packages/fastcore/foundation.py", line 250, in _listify
    if is_iter(o): return list(o)
  File "/home/nole/.local/lib/python3.7/site-packages/fastcore/foundation.py", line 216, in __call__
    return self.fn(*fargs, **kwargs)
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 127, in _call_one
    [cb(event_name) for cb in sort_by_run(self.cbs)]
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 127, in <listcomp>
    [cb(event_name) for cb in sort_by_run(self.cbs)]
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/callback/core.py", line 24, in __call__
    if self.run and _run: getattr(self, event_name, noop)()
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/callback/core.py", line 95, in after_validate
    if self.with_input:     self.inputs  = detuplify(to_concat(self.inputs, dim=self.concat_dim))
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/torch_core.py", line 213, in to_concat
    if is_listy(xs[0]): return type(xs[0])([to_concat([x[i] for x in xs], dim=dim) for i in range_of(xs[0])])
IndexError: list index out of range
WARNING:  Detected file change in 'main.py'. Reloading...
dict_keys(['CN1S', 'CN1SDR3', 'CN1SRP', 'CN1SRP6', 'CN2SO', 'CNSOD', 'I-210+cn', 'I-210+n', 'kv', 'kv2c', 'kv2c_a_base'])
Traceback (most recent call last):-----| 0.00% [0/1 00:00<00:00]
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.7/multiprocessing/spawn.py", line 105, in spawn_main
  File "/usr/lib/python3.7/multiprocessing/spawn.py", line 105, in spawn_main
    exitcode = _main(fd)
    exitcode = _main(fd)
  File "/usr/lib/python3.7/multiprocessing/spawn.py", line 115, in _main
  File "/usr/lib/python3.7/multiprocessing/spawn.py", line 115, in _main
    self = reduction.pickle.load(from_parent)
    self = reduction.pickle.load(from_parent)
AttributeError: '_FakeLoader' object has no attribute 'noops'
AttributeError: '_FakeLoader' object has no attribute 'noops'
Process SpawnProcess-3:                                         
Traceback (most recent call last):
  File "/home/nole/.local/lib/python3.7/site-packages/torch/utils/data/dataloader.py", line 761, in _try_get_data
    data = self._data_queue.get(timeout=timeout)
  File "/usr/lib/python3.7/multiprocessing/queues.py", line 104, in get
    if not self._poll(timeout):
  File "/usr/lib/python3.7/multiprocessing/connection.py", line 257, in poll
    return self._poll(timeout)
  File "/usr/lib/python3.7/multiprocessing/connection.py", line 414, in _poll
    r = wait([self], timeout)
  File "/usr/lib/python3.7/multiprocessing/connection.py", line 920, in wait
    ready = selector.select(timeout)
  File "/usr/lib/python3.7/selectors.py", line 415, in select
    fd_event_list = self._selector.poll(timeout)
  File "/home/nole/.local/lib/python3.7/site-packages/torch/utils/data/_utils/signal_handling.py", line 66, in handler
    _error_if_any_worker_fails()
RuntimeError: DataLoader worker (pid 22478) exited unexpectedly with exit code 1. Details are lost due to multiprocessing. Rerunning with num_workers=0 may give better error trace.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 175, in _do_epoch_validate
    with torch.no_grad(): self.all_batches()
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 143, in all_batches
    for o in enumerate(self.dl): self.one_batch(*o)
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/data/load.py", line 97, in __iter__
    for b in _loaders[self.fake_l.num_workers==0](self.fake_l):
  File "/home/nole/.local/lib/python3.7/site-packages/torch/utils/data/dataloader.py", line 345, in __next__
    data = self._next_data()
  File "/home/nole/.local/lib/python3.7/site-packages/torch/utils/data/dataloader.py", line 841, in _next_data
    idx, data = self._get_data()
  File "/home/nole/.local/lib/python3.7/site-packages/torch/utils/data/dataloader.py", line 808, in _get_data
    success, data = self._try_get_data()
  File "/home/nole/.local/lib/python3.7/site-packages/torch/utils/data/dataloader.py", line 774, in _try_get_data
    raise RuntimeError('DataLoader worker (pid(s) {}) exited unexpectedly'.format(pids_str))
RuntimeError: DataLoader worker (pid(s) 22478, 22479) exited unexpectedly

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.7/multiprocessing/process.py", line 297, in _bootstrap
    self.run()
  File "/usr/lib/python3.7/multiprocessing/process.py", line 99, in run
    self._target(*self._args, **self._kwargs)
  File "/home/nole/.local/lib/python3.7/site-packages/uvicorn/subprocess.py", line 61, in subprocess_started
    target(sockets=sockets)
  File "/home/nole/.local/lib/python3.7/site-packages/uvicorn/main.py", line 382, in run
    loop.run_until_complete(self.serve(sockets=sockets))
  File "uvloop/loop.pyx", line 1456, in uvloop.loop.Loop.run_until_complete
  File "/home/nole/.local/lib/python3.7/site-packages/uvicorn/main.py", line 389, in serve
    config.load()
  File "/home/nole/.local/lib/python3.7/site-packages/uvicorn/config.py", line 288, in load
    self.loaded_app = import_from_string(self.app)
  File "/home/nole/.local/lib/python3.7/site-packages/uvicorn/importer.py", line 20, in import_from_string
    module = importlib.import_module(module_str)
  File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "./main.py", line 13, in <module>
    prediction, loc, prob_classes = learn_inf.predict(img)
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 231, in predict
    inp,preds,_,dec_preds = self.get_preds(dl=dl, with_input=True, with_decoded=True)
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 219, in get_preds
    self._do_epoch_validate(dl=dl)
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 178, in _do_epoch_validate
    dl,*_ = change_attrs(dl, names, old, has);       self('after_validate')
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 124, in __call__
    def __call__(self, event_name): L(event_name).map(self._call_one)
  File "/home/nole/.local/lib/python3.7/site-packages/fastcore/foundation.py", line 372, in map
    return self._new(map(g, self))
  File "/home/nole/.local/lib/python3.7/site-packages/fastcore/foundation.py", line 323, in _new
    def _new(self, items, *args, **kwargs): return type(self)(items, *args, use_list=None, **kwargs)
  File "/home/nole/.local/lib/python3.7/site-packages/fastcore/foundation.py", line 41, in __call__
    res = super().__call__(*((x,) + args), **kwargs)
  File "/home/nole/.local/lib/python3.7/site-packages/fastcore/foundation.py", line 314, in __init__
    items = list(items) if use_list else _listify(items)
  File "/home/nole/.local/lib/python3.7/site-packages/fastcore/foundation.py", line 250, in _listify
    if is_iter(o): return list(o)
  File "/home/nole/.local/lib/python3.7/site-packages/fastcore/foundation.py", line 216, in __call__
    return self.fn(*fargs, **kwargs)
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 127, in _call_one
    [cb(event_name) for cb in sort_by_run(self.cbs)]
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/learner.py", line 127, in <listcomp>
    [cb(event_name) for cb in sort_by_run(self.cbs)]
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/callback/core.py", line 24, in __call__
    if self.run and _run: getattr(self, event_name, noop)()
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/callback/core.py", line 95, in after_validate
    if self.with_input:     self.inputs  = detuplify(to_concat(self.inputs, dim=self.concat_dim))
  File "/home/nole/.local/lib/python3.7/site-packages/fastai2/torch_core.py", line 213, in to_concat
    if is_listy(xs[0]): return type(xs[0])([to_concat([x[i] for x in xs], dim=dim) for i in range_of(xs[0])])
IndexError: list index out of range

Using this code with starlette does work:

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
from fastai2.vision.all import *

path = Path()
path.ls(file_exts='.pkl')

learn_inf = load_learner(path/'export.pkl')
vocab = learn_inf.dls.vocab.o2i.keys()
print(vocab)

img= Path("./index.jpeg")
prediction, loc, prob_classes = learn_inf.predict(img)
print(prediction, loc, prob_classes)


async def homepage(request):
    return JSONResponse({'hello': 'world'})


app = Starlette(debug=True, routes=[
    Route('/', homepage),
])

output:

I-210+n tensor(7) tensor([7.9076e-08, 4.3723e-05, 9.5849e-06, 9.9134e-04, 7.5235e-08, 4.8674e-04,
        1.0136e-02, 6.0512e-01, 3.8291e-01, 8.4351e-05, 2.2064e-04])

This is a little dissapointing because I was looking forward to using FastAPI. But I think it means there’s something funky going on with it. Despite it being built ontop of starlette

@nole which version of python did you use to train/pickle your model? I see you’re using 3.7 to run your Flask app.

I ran into this exact issue today. I had trained my model in Google Collaboratory with python 3.6.9 but tried running my Flask app locally with python 3.8.2 after creating a new pipenv environment.

I’m not sure if this is relevant for you, but I wanted to share because this post is the only documentation of this error I could find.

Good luck!

Hello, thanks for the reply. I also trained my model on colab with 3.6.9. On ubuntu I’ve got 3.7.5 Can you please tell me how you fixed your problem? I have tried:

  • making a docker container with python 3.6
  • installing everything on windows
  • using no cuda drivers from the torch packages
  • using the fastai2-starlette repo

and cannot get any of it to work. And on top of that now my original starlette code doesn’t work for reasons I cannot understand.

EDIT: I finally got a docker container working from my windows machine that uses fastai2 and fastapi. Once I get it on par with the starlette repo for fastai2 I will post the repo link. (assuming it does not break again)

EDIT2: github link https://github.com/BoxOfCereal/FastAPI-Fastai2

@nole, I’m sorry to hear that.

During local development, I installed 3.6.9 with pyenv and had success.
For Docker, I used the python:3.6-slim-buster base image and also had success.

You can see the repo here: https://github.com/Thomascountz/pigeon

As an added layer of complexity, I’m also using pipenv to manage my local environment. As per the Pipfile you can see I’ve declared "3.6" as the python version.

Thanks for the reply @thomascountz. I’d love to see the pipenv settings. I haven’t been able to get it to work on either my ubuntu or windows machine. And, having a working docker file example will be nice. I’m still pretty new to using it. Thanks again.

1 Like

I’m getting a very similar error @nole, also from trying to use Fastai2 with FastAPI. Did you ever work out what exactly the problem was?

I did, for a while. I’ve not been able to get fastai 1 or 2 working well with windows so I dockerized it. Here’s the repo I made that was working. Unfortunately now I’m getting this error:

Traceback (most recent call last):
  File "app/server.py", line 4, in <module>
    from fastai2.vision.all import *
  File "/usr/local/lib/python3.7/site-packages/fastai2/vision/all.py", line 1, in <module>
    from ..basics import *
  File "/usr/local/lib/python3.7/site-packages/fastai2/basics.py", line 1, in <module>
    from .data.all import *
  File "/usr/local/lib/python3.7/site-packages/fastai2/data/all.py", line 1, in <module>
    from ..torch_basics import *
  File "/usr/local/lib/python3.7/site-packages/fastai2/torch_basics.py", line 4, in <module>
    from .torch_core import *
  File "/usr/local/lib/python3.7/site-packages/fastai2/torch_core.py", line 246, in <module>
    setattr(torch, 'as_subclass', torch.Tensor.as_subclass)
AttributeError: type object 'Tensor' has no attribute 'as_subclass'

You need torch 1.6

I’ll try this thank you

fastapi[all]
torch==1.5.0+cpu <---  torch==1.6.0+cpu
torchvision==0.6.0+cpu

@muellerzr That worked perfectly! Thank you so much! You’ve helped a few times now and I really appreciate it! :slight_smile:

@HenryDashwood
I updated the repo and now it should just be plug in your exported model’s location and play. The readme has all the info.

1 Like

I have a slightly different use case which is where I’m struggling. I’m trying to finetune a model in my endpoint rather than just make a prediction. After throwing a couple of AttributeError: '_FakeLoader' object has no attribute 'noops' errors which come from fastai2, it gives RuntimeError: DataLoader worker (pid(s) 26750, 26761, 26772, 26781, 26792, 26803, 26814, 26823) exited unexpectedly which is a torch dataloader error.

Can you post your sever.py? Or where you init the library and the endpoint?

Here is a minimal example to replicate. I should add that this is on a Mac with python 3.7.4

import pandas as pd
from fastapi import FastAPI
from fastai2.text.all import *

app = FastAPI()

@app.get('/api/session/')
def suggest_textitems():
    df = pd.DataFrame()
    df_len = 150
    df['text'] = [f'text example {i}' for i in range(df_len)]
    df['label'] = [0] * (df_len//2) + [1] * (df_len//2)

    dls_cl = TextDataLoaders.from_df(
        df,
        text_col='text',
        label_col='label',
        valid_pct=0.1,
        bs=32
    )

    learn = text_classifier_learner(
        dls_cl,
        AWD_LSTM,
        drop_mult=0.5,
        metrics=accuracy
    )
    learn.fit_one_cycle(1)

    return {'success': True}

I’m not really familiar with the text portion. Although I have not had any luck on windows. Is it possible to try on linux?

Hi! I don’t know if it helps, I just stumbled upon this error myself. I think it have sth to do with multiprocessing and running “regular” fastai code in another process.

I have a code that does data loading->training->evaluation->save some losses. I am trying to make this work in multiple processes. No luck, yet but now I am at this error _FakeLoader' object has no attribute 'noops for which google of course showed me this page.

I am still digging for a solution but flask is also starting some processes. And my code works smooth in non-multiprocessing setup. So, back to googling!

p.s. Maybe it has nothing to do with fast.ai, but to the way the pocesses are spawned/foked/started/daemonized.

Hope it helps.

L.E. Classical num_workers=0 works. However, no solution yet. Enough problems with sharing cuda context while being able to use classical locks. And no quick way to use Pool() :frowning: