Why do I get NameNotFound: Environment FrostbiteDeterministic doesn't exist, when using gym environments? - openai-gym

I am encountering the NameNotFound error, when I run the following code -
import gym
env = gym.make("FrostbiteDeterministic-v4")
observation, info = env.reset(seed=42, return_info=True)
for _ in range(1000):
action = env.action_space.sample()
observation, reward, done, info = env.step(action)
if done:
observation, info = env.reset(return_info=True)
env.close()
Here is the traceback -
NameNotFound Traceback (most recent call last)
Input In [10], in <cell line: 2>()
1 import gym
----> 2 env = gym.make("FrostbiteDeterministic-v4")
3 observation, info = env.reset(seed=42, return_info=True)
5 for _ in range(1000):
File ~\Anaconda3\envs\test\lib\site-packages\gym\envs\registration.py:578, in make(id, max_episode_steps, autoreset, disable_env_checker, **kwargs)
572 logger.warn(
573 f"Using the latest versioned environment `{new_env_id}` "
574 f"instead of the unversioned environment `{id}`."
575 )
577 if spec_ is None:
--> 578 _check_version_exists(ns, name, version)
579 raise error.Error(f"No registered env with id: {id}")
581 _kwargs = spec_.kwargs.copy()
File ~\Anaconda3\envs\test\lib\site-packages\gym\envs\registration.py:209, in _check_version_exists(ns, name, version)
206 if get_env_id(ns, name, version) in registry:
207 return
--> 209 _check_name_exists(ns, name)
210 if version is None:
211 return
File ~\Anaconda3\envs\test\lib\site-packages\gym\envs\registration.py:187, in _check_name_exists(ns, name)
184 namespace_msg = f" in namespace {ns}" if ns else ""
185 suggestion_msg = f"Did you mean: `{suggestion[0]}`?" if suggestion else ""
--> 187 raise error.NameNotFound(
188 f"Environment {name} doesn't exist{namespace_msg}. {suggestion_msg}"
189 )
NameNotFound: Environment FrostbiteDeterministic doesn't exist.
I believe the environment should exist since people have used it over here - https://github.com/openai/gym/issues/1478
Perhaps it doesn't work with a later version of OpenAI gym?

Related

Huggingface tokenizer not able to load model after upgrading python to 3.10

I just updated Python to version 3.10.8. Note that I use JupyterLab.
I had to re-install a lot of packages, but now I get an error when I try to load the tokenizer of an HuggingFace model
This is my code:
# Import libraries
from transformers import pipeline, AutoTokenizer
# Define checkpoint
model_checkpoint = 'deepset/xlm-roberta-large-squad2'
# Tokenizer
tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
Note that version of transformers is 4.24.0.
This is the error I get:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In [3], line 2
1 # Tokenizer
----> 2 tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
File ~/.local/lib/python3.10/site-packages/transformers/models/auto/tokenization_auto.py:637, in AutoTokenizer.from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs)
635 tokenizer_class_py, tokenizer_class_fast = TOKENIZER_MAPPING[type(config)]
636 if tokenizer_class_fast and (use_fast or tokenizer_class_py is None):
--> 637 return tokenizer_class_fast.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
638 else:
639 if tokenizer_class_py is not None:
File ~/.local/lib/python3.10/site-packages/transformers/tokenization_utils_base.py:1777, in PreTrainedTokenizerBase.from_pretrained(cls, pretrained_model_name_or_path, *init_inputs, **kwargs)
1774 else:
1775 logger.info(f"loading file {file_path} from cache at {resolved_vocab_files[file_id]}")
-> 1777 return cls._from_pretrained(
1778 resolved_vocab_files,
1779 pretrained_model_name_or_path,
1780 init_configuration,
1781 *init_inputs,
1782 use_auth_token=use_auth_token,
1783 cache_dir=cache_dir,
1784 local_files_only=local_files_only,
1785 _commit_hash=commit_hash,
1786 **kwargs,
1787 )
File ~/.local/lib/python3.10/site-packages/transformers/tokenization_utils_base.py:1932, in PreTrainedTokenizerBase._from_pretrained(cls, resolved_vocab_files, pretrained_model_name_or_path, init_configuration, use_auth_token, cache_dir, local_files_only, _commit_hash, *init_inputs, **kwargs)
1930 # Instantiate tokenizer.
1931 try:
-> 1932 tokenizer = cls(*init_inputs, **init_kwargs)
1933 except OSError:
1934 raise OSError(
1935 "Unable to load vocabulary from file. "
1936 "Please check that the provided vocabulary is accessible and not corrupted."
1937 )
File ~/.local/lib/python3.10/site-packages/transformers/models/xlm_roberta/tokenization_xlm_roberta_fast.py:155, in XLMRobertaTokenizerFast.__init__(self, vocab_file, tokenizer_file, bos_token, eos_token, sep_token, cls_token, unk_token, pad_token, mask_token, **kwargs)
139 def __init__(
140 self,
141 vocab_file=None,
(...)
151 ):
152 # Mask token behave like a normal word, i.e. include the space before it
153 mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
--> 155 super().__init__(
156 vocab_file,
157 tokenizer_file=tokenizer_file,
158 bos_token=bos_token,
159 eos_token=eos_token,
160 sep_token=sep_token,
161 cls_token=cls_token,
162 unk_token=unk_token,
163 pad_token=pad_token,
164 mask_token=mask_token,
165 **kwargs,
166 )
168 self.vocab_file = vocab_file
169 self.can_save_slow_tokenizer = False if not self.vocab_file else True
File ~/.local/lib/python3.10/site-packages/transformers/tokenization_utils_fast.py:114, in PreTrainedTokenizerFast.__init__(self, *args, **kwargs)
111 fast_tokenizer = TokenizerFast.from_file(fast_tokenizer_file)
112 elif slow_tokenizer is not None:
113 # We need to convert a slow tokenizer to build the backend
--> 114 fast_tokenizer = convert_slow_tokenizer(slow_tokenizer)
115 elif self.slow_tokenizer_class is not None:
116 # We need to create and convert a slow tokenizer to build the backend
117 slow_tokenizer = self.slow_tokenizer_class(*args, **kwargs)
File ~/.local/lib/python3.10/site-packages/transformers/convert_slow_tokenizer.py:1162, in convert_slow_tokenizer(transformer_tokenizer)
1154 raise ValueError(
1155 f"An instance of tokenizer class {tokenizer_class_name} cannot be converted in a Fast tokenizer instance."
1156 " No converter was found. Currently available slow->fast convertors:"
1157 f" {list(SLOW_TO_FAST_CONVERTERS.keys())}"
1158 )
1160 converter_class = SLOW_TO_FAST_CONVERTERS[tokenizer_class_name]
-> 1162 return converter_class(transformer_tokenizer).converted()
File ~/.local/lib/python3.10/site-packages/transformers/convert_slow_tokenizer.py:438, in SpmConverter.__init__(self, *args)
434 requires_backends(self, "protobuf")
436 super().__init__(*args)
--> 438 from .utils import sentencepiece_model_pb2 as model_pb2
440 m = model_pb2.ModelProto()
441 with open(self.original_tokenizer.vocab_file, "rb") as f:
File ~/.local/lib/python3.10/site-packages/transformers/utils/sentencepiece_model_pb2.py:20
18 from google.protobuf import descriptor as _descriptor
19 from google.protobuf import message as _message
---> 20 from google.protobuf import reflection as _reflection
21 from google.protobuf import symbol_database as _symbol_database
24 # ##protoc_insertion_point(imports)
File /usr/lib/python3/dist-packages/google/protobuf/reflection.py:58
56 from google.protobuf.pyext import cpp_message as message_impl
57 else:
---> 58 from google.protobuf.internal import python_message as message_impl
60 # The type of all Message classes.
61 # Part of the public interface, but normally only used by message factories.
62 GeneratedProtocolMessageType = message_impl.GeneratedProtocolMessageType
File /usr/lib/python3/dist-packages/google/protobuf/internal/python_message.py:69
66 import copyreg as copyreg
68 # We use "as" to avoid name collisions with variables.
---> 69 from google.protobuf.internal import containers
70 from google.protobuf.internal import decoder
71 from google.protobuf.internal import encoder
File /usr/lib/python3/dist-packages/google/protobuf/internal/containers.py:182
177 collections.MutableMapping.register(MutableMapping)
179 else:
180 # In Python 3 we can just use MutableMapping directly, because it defines
181 # __slots__.
--> 182 MutableMapping = collections.MutableMapping
185 class BaseContainer(object):
187 """Base container class."""
AttributeError: module 'collections' has no attribute 'MutableMapping'
I tried several solutions (for example, this and this), but none seem to work.
According to this link, I should change collections.Mapping into collections.abc.Mapping, but I wouldn't knwo where to do it.
Another possible solution is downgrading Python to 3.9, but I would like to keep it as last resort.
How can I fix this?
Turned out it was a problem related to protobuf module. I updated it to the latest version to date (which is 4.21.9).
This changed the error to:
TypeError: Descriptors cannot not be created directly.
If this call came from a _pb2.py file, your generated code is out of date and must be regenerated with protoc >= 3.19.0.
If you cannot immediately regenerate your protos, some other possible workarounds are:
1. Downgrade the protobuf package to 3.20.x or lower.
2. Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python (but this will use pure-Python parsing and will be much slower).
More information: https://developers.google.com/protocol-buffers/docs/news/2022-05-06#python-updates
So I downgraded protobuf to version 3.20.0 and that worked.
For further details, look here.

Problem loading trained scikit-learn/imblearn pipeline model

I have built, trained an imblearn.pipeline Pipeline with imblearn and RandomForestClassifer from Scikit-learn.
The model is saved using joblib.dump('model.joblib').
However, when I try to load the model, it throws an error
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-26-d3ee277020d2> in <module>
----> 1 model = joblib.load('model.joblib')
~/SageMaker/custom-miniconda/miniconda/envs/datascience/lib/python3.7/site-packages/joblib/numpy_pickle.py in load(filename, mmap_mode)
583 return load_compatibility(fobj)
584
--> 585 obj = _unpickle(fobj, filename, mmap_mode)
586 return obj
~/SageMaker/custom-miniconda/miniconda/envs/datascience/lib/python3.7/site-packages/joblib/numpy_pickle.py in _unpickle(fobj, filename, mmap_mode)
502 obj = None
503 try:
--> 504 obj = unpickler.load()
505 if unpickler.compat_mode:
506 warnings.warn("The file '%s' has been generated with a "
~/SageMaker/custom-miniconda/miniconda/envs/datascience/lib/python3.7/pickle.py in load(self)
1086 raise EOFError
1087 assert isinstance(key, bytes_types)
-> 1088 dispatch[key[0]](self)
1089 except _Stop as stopinst:
1090 return stopinst.value
~/SageMaker/custom-miniconda/miniconda/envs/datascience/lib/python3.7/pickle.py in load_global(self)
1374 module = self.readline()[:-1].decode("utf-8")
1375 name = self.readline()[:-1].decode("utf-8")
-> 1376 klass = self.find_class(module, name)
1377 self.append(klass)
1378 dispatch[GLOBAL[0]] = load_global
~/SageMaker/custom-miniconda/miniconda/envs/datascience/lib/python3.7/pickle.py in find_class(self, module, name)
1424 elif module in _compat_pickle.IMPORT_MAPPING:
1425 module = _compat_pickle.IMPORT_MAPPING[module]
-> 1426 __import__(module, level=0)
1427 if self.proto >= 4:
1428 return _getattribute(sys.modules[module], name)[0]
ModuleNotFoundError: No module named 'imblearn.over_sampling._smote.base'; 'imblearn.over_sampling._smote' is not a package
I do have imblearn installed in the conda environment. Not sure why it's not finding imblearn. Any tips will be helpful.
use
python-m pip install package name
to install it globally on system ,maybe it can help

Some mistakes when I reload "torch.nn.functioanl"?

I want to modify some functions in "torch.nn.functional", and then I use "importlib.reload" to reload the new "torch.nn.functional".But I encounter a Runtime error:function 'avg_pool2d' already has a docstring.
I am trying to do some work on excitationbp(https://github.com/greydanus/excitationbp), and there is a operation named "eb.use_eb()" to modify "torch.nn.functional". The functiona eb.use_eb() is for modifying the "torch.nn.linear","torch.nn.functional.conv1d" and so on.I try to modify the code including many eb.use_eb() in the utils.py.When I want to run the original "torch.nn.linear",I must run the eb.use_eb(False).But the module has loaded in the head of the file(import torch.nn.funtional). So I want to reload the module "torch.nn.funtional".
When I use the "importlib.reload", I encounter a error.
eb.use_eb(False,True)
importlib.reload(torch)
importlib.reload(torch.nn)
importlib.reload(torch.nn.functional)
print("gradient_evidence:"+str(gradient_evidence))
return torch.autograd.grad(contr_h_, target_h_, grad_outputs=gradient_evidence)[0]
RuntimeError Traceback (most recent call last)
ipython-input-15-29d0fca29882 in module()
----> 1 prob_inputs_one = eb.excitation_backprop(model, inputs, prob_outputs_one, contrastive=2)
2 #pdb.set_trace()
3 prob_inputs_true = eb.excitation_backprop(model, inputs, prob_outputs_true, contrastive=2)
~/code/excitationbp/excitationbp-master/excitationbp/utils.py in excitation_backprop(model, inputs, prob_outputs, contrastive, target_layer)
75 importlib.reload(torch)
76 importlib.reload(torch.nn)
---> 77 importlib.reload(torch.nn.functional)
78
79 gradient_evidence = torch.autograd.grad(top_h_, contr_h_, grad_outputs=prob_outputs.clone())[0]
~/anaconda3/envs/pytorch0.3/lib/python3.6/importlib/__init__.py in reload(module)
164 target = module
165 spec = module.__spec__ = _bootstrap._find_spec(name, pkgpath, target)
--> 166 _bootstrap._exec(spec, module)
167 # The module may have replaced itself in sys.modules!
168 return sys.modules[name]
~/anaconda3/envs/pytorch0.3/lib/python3.6/importlib/_bootstrap.py in _exec(spec, module)
~/anaconda3/envs/pytorch0.3/lib/python3.6/importlib/_bootstrap_external.py in exec_module(self, module)
~/anaconda3/envs/pytorch0.3/lib/python3.6/importlib/_bootstrap.py in _call_with_frames_removed(f, *args, **kwds)
~/anaconda3/envs/pytorch0.3/lib/python3.6/site-packages/torch/nn/functional.py in <module>()
286 count_include_pad: when True, will include the zero-padding in th
287 averaging calculation. Default: ``True``
--> 288 """)
289
290 avg_pool3d = _add_docstr(torch._C._nn.avg_pool3d, r"""
RuntimeError: function 'avg_pool2d' already has a docstring

Google Colab - tensowflow object detection api - 'function' object has no attribute 'called'

I encountered the following error when I try to test the object detection api model_builder_test.py.
!apt-get install -y -qq protobuf-compiler python-pil python-lxml
!git clone --quiet https://github.com/tensorflow/models.git
import os
os.chdir('models/research')
!protoc object_detection/protos/*.proto --python_out=.
import sys
sys.path.append('/content/models/research/slim')
%run object_detection/builders/model_builder_test.py
The following error appears after running the model_builder_test.py
.W0220 03:22:35.097244 140099951081344 deprecation.py:323] From
/content/models/research/object_detection/anchor_generators/grid_anchor_generator.py:59:
to_float (from tensorflow.python.ops.math_ops) is deprecated and will
be removed in a future version. Instructions for updating: Use tf.cast
instead. .. WARNING: The TensorFlow contrib module will not be
included in TensorFlow 2.0. For more information, please see: *
https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md
* https://github.com/tensorflow/addons If you depend on functionality not listed there, please file an issue.
..................s
---------------------------------------------------------------------- Ran 22 tests in 0.203s
OK (skipped=1)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call
last) in ()
----> 1 get_ipython().magic('run object_detection/builders/model_builder_test.py')
/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py
in magic(self, arg_s) 2158 magic_name, _, magic_arg_s =
arg_s.partition(' ') 2159 magic_name =
magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2160 return self.run_line_magic(magic_name, magic_arg_s) 2161 2162
-------------------------------------------------------------------------
/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py
in run_line_magic(self, magic_name, line) 2079
kwargs['local_ns'] = sys._getframe(stack_depth).f_locals 2080
with self.builtin_trap:
-> 2081 result = fn(*args,**kwargs) 2082 return result 2083
in run(self, parameter_s, runner, file_finder)
/usr/local/lib/python3.6/dist-packages/IPython/core/magic.py in
(f, *a, **k)
186 # but it's overkill for just that one bit of state.
187 def magic_deco(arg):
--> 188 call = lambda f, *a, **k: f(*a, **k)
189
190 if callable(arg):
/usr/local/lib/python3.6/dist-packages/IPython/core/magics/execution.py
in run(self, parameter_s, runner, file_finder)
740 else:
741 # regular execution
--> 742 run()
743
744 if 'i' in opts:
/usr/local/lib/python3.6/dist-packages/IPython/core/magics/execution.py
in run()
726 def run():
727 runner(filename, prog_ns, prog_ns,
--> 728 exit_ignore=exit_ignore)
729
730 if 't' in opts:
/usr/local/lib/python3.6/dist-packages/IPython/core/pylabtools.py in
mpl_execfile(fname, *where, **kw)
175 matplotlib.interactive(is_interactive)
176 # make rendering call now, if the user tried to do it
--> 177 if plt.draw_if_interactive.called:
178 plt.draw()
179 plt.draw_if_interactive.called = False
AttributeError: 'function' object has no attribute 'called'
This is how I overcame the issue:
install prompt-toolkit to the version 1.0.15, as explained in the link below
https://github.com/jupyter/jupyter_console/issues/158
restart the runtime to activate the package
use '!python' instead of '%run'

Ipython notebook "from mpl_toolkits.mplot3d import Axes3D" has Value Error

I started learning Python 4 months ago and nearly everything went perfect until I got an excercise, where I have to do 3d plots.
For that I have to import mpl_toolkits.mplit3d, but I get this error:
ValueError Traceback (most recent call last)
<ipython-input-3-c39f93eee133> in <module>()
----> 1 get_ipython().magic('matplotlib notebook')
2 from pylab import *
3 from mpl_toolkits.mplot3d import Axes3D
4
5 Lp = 200
/usr/local/lib/python3.4/dist-packages/IPython/core/interactiveshell.py in magic(self, arg_s)
2334 magic_name, _, magic_arg_s = arg_s.partition(' ')
2335 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2336 return self.run_line_magic(magic_name, magic_arg_s)
2337
2338 #-------------------------------------------------------------------------
/usr/local/lib/python3.4/dist-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line)
2255 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2256 with self.builtin_trap:
-> 2257 result = fn(*args,**kwargs)
2258 return result
2259
/usr/local/lib/python3.4/dist-packages/IPython/core/magics/pylab.py in matplotlib(self, line)
/usr/local/lib/python3.4/dist-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
191 # but it's overkill for just that one bit of state.
192 def magic_deco(arg):
--> 193 call = lambda f, *a, **k: f(*a, **k)
194
195 if callable(arg):
/usr/local/lib/python3.4/dist-packages/IPython/core/magics/pylab.py in matplotlib(self, line)
98 print("Available matplotlib backends: %s" % backends_list)
99 else:
--> 100 gui, backend = self.shell.enable_matplotlib(args.gui)
101 self._show_matplotlib_backend(args.gui, backend)
102
/usr/local/lib/python3.4/dist-packages/IPython/core/interactiveshell.py in enable_matplotlib(self, gui)
3130 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3131
-> 3132 pt.activate_matplotlib(backend)
3133 pt.configure_inline_support(self, backend)
3134
/usr/local/lib/python3.4/dist-packages/IPython/core/pylabtools.py in activate_matplotlib(backend)
270 # the rcParam to update. This needs to be set *before* the module
271 # magic of switch_backend().
--> 272 matplotlib.rcParams['backend'] = backend
273
274 import matplotlib.pyplot
/usr/lib/python3/dist-packages/matplotlib/__init__.py in __setitem__(self, key, val)
808 warnings.warn(self.msg_depr_ignore % (key, alt))
809 return
--> 810 cval = self.validate[key](val)
811 dict.__setitem__(self, key, cval)
812 except KeyError:
/usr/lib/python3/dist-packages/matplotlib/rcsetup.py in validate_backend(s)
144 return s
145 else:
--> 146 return _validate_standard_backends(s)
147
148 validate_qt4 = ValidateInStrings('backend.qt4', ['PyQt4', 'PySide'])
/usr/lib/python3/dist-packages/matplotlib/rcsetup.py in __call__(self, s)
55 return self.valid[s]
56 raise ValueError('Unrecognized %s string "%s": valid strings are %s'
---> 57 % (self.key, s, list(self.valid.values())))
58
59
ValueError: Unrecognized backend string "nbagg": valid strings are ['GTK', 'template', 'svg', 'Qt4Agg', 'GTK3Cairo', 'emf', 'WX', 'GTK3Agg', 'CocoaAgg', 'WebAgg', 'TkAgg', 'agg', 'gdk', 'GTKAgg', 'cairo', 'ps', 'pdf', 'pgf', 'WXAgg', 'MacOSX', 'GTKCairo']
I really dont know what that means.
Obviously, I have this package, so what is the problem?

Resources